"""Phase 9.3 — Coach & Staff Management schema."""
from alembic import op
import sqlalchemy as sa
from app.core.database import Base
import app.models  # noqa: F401

revision = "0004_phase_93_coach_staff"
down_revision = "0003_phase_92_member_management"
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    columns = {c["name"] for c in sa.inspect(bind).get_columns("coaches")}
    with op.batch_alter_table("coaches") as batch:
        for col_name, col_type in (
            ("staff_kind", sa.String(32)),
            ("bio", sa.Text()),
            ("hire_date", sa.Date()),
            ("payroll_external_ref", sa.String(100)),
            ("sports_role_id", sa.String(36)),
        ):
            if col_name not in columns:
                batch.add_column(sa.Column(col_name, col_type, nullable=True))
    Base.metadata.create_all(bind=bind)


def downgrade():
    bind = op.get_bind()
    for table in (
        "staff_assignments",
        "staff_availability",
        "staff_working_hours",
        "staff_skills",
        "staff_certificates",
    ):
        if sa.inspect(bind).has_table(table):
            op.drop_table(table)
    columns = {c["name"] for c in sa.inspect(bind).get_columns("coaches")}
    with op.batch_alter_table("coaches") as batch:
        for col in (
            "staff_kind",
            "bio",
            "hire_date",
            "payroll_external_ref",
            "sports_role_id",
        ):
            if col in columns:
                batch.drop_column(col)
