"""Phase 9.2 — Member Management schema."""
from alembic import op
import sqlalchemy as sa
from app.core.database import Base
import app.models  # noqa: F401

revision = "0003_phase_92_member_management"
down_revision = "0002_phase_91_membership_catalog"
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    columns = {c["name"] for c in sa.inspect(bind).get_columns("memberships")}
    with op.batch_alter_table("memberships") as batch:
        if "member_id" not in columns:
            batch.add_column(sa.Column("member_id", sa.String(36), nullable=True))
        if "freeze_starts_on" not in columns:
            batch.add_column(sa.Column("freeze_starts_on", sa.Date(), nullable=True))
        if "freeze_ends_on" not in columns:
            batch.add_column(sa.Column("freeze_ends_on", sa.Date(), nullable=True))
    Base.metadata.create_all(bind=bind)


def downgrade():
    bind = op.get_bind()
    for table in (
        "member_documents",
        "waivers",
        "digital_memberships",
        "membership_cards",
        "medical_information",
        "emergency_contacts",
        "family_members",
        "members",
    ):
        if sa.inspect(bind).has_table(table):
            op.drop_table(table)
    columns = {c["name"] for c in sa.inspect(bind).get_columns("memberships")}
    with op.batch_alter_table("memberships") as batch:
        for col in ("member_id", "freeze_starts_on", "freeze_ends_on"):
            if col in columns:
                batch.drop_column(col)
