"""add psap_boundaries table

Revision ID: f7400dfdcdc5
Revises: 6c4f7f1b9d2a
Create Date: 2026-02-20 11:04:59.300192

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from geoalchemy2 import Geometry


# revision identifiers, used by Alembic.
revision: str = 'f7400dfdcdc5'
down_revision: Union[str, Sequence[str], None] = '6c4f7f1b9d2a'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Upgrade schema."""
    # Ensure PostGIS extension is enabled
    op.execute("CREATE EXTENSION IF NOT EXISTS postgis")

    # Create psap_boundaries table
    op.create_table(
        "psap_boundaries",
        sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column("objectid", sa.Integer(), nullable=True),
        sa.Column("psap_id", sa.Text(), nullable=True),
        sa.Column("name", sa.Text(), nullable=False),
        sa.Column("psap_name", sa.Text(), nullable=True),
        sa.Column("fcc_id", sa.Text(), nullable=True),
        sa.Column("state_id", sa.Text(), nullable=True),
        sa.Column("telephone", sa.Text(), nullable=True),
        sa.Column("address", sa.Text(), nullable=True),
        sa.Column("address2", sa.Text(), nullable=True),
        sa.Column("city", sa.Text(), nullable=True),
        sa.Column("state", sa.Text(), nullable=True),
        sa.Column("zip", sa.Text(), nullable=True),
        sa.Column("county", sa.Text(), nullable=True),
        sa.Column("fips", sa.Text(), nullable=True),
        sa.Column("web", sa.Text(), nullable=True),
        sa.Column("update_date", sa.Text(), nullable=True),
        sa.Column("boundary", Geometry(geometry_type="MULTIPOLYGON", srid=3857), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
        sa.PrimaryKeyConstraint("id", name=op.f("psap_boundaries_pkey")),
        sa.UniqueConstraint("objectid", name=op.f("psap_boundaries_objectid_key")),
    )

    # Create non-spatial indexes only
    # Note: Spatial index (GIST) is created automatically by PostGIS/GeoAlchemy2
    op.create_index("idx_psap_boundaries_state", "psap_boundaries", ["state"])
    op.create_index("idx_psap_boundaries_objectid", "psap_boundaries", ["objectid"])
    op.create_index("idx_psap_boundaries_city", "psap_boundaries", ["city"])


def downgrade() -> None:
    """Downgrade schema."""
    op.drop_index("idx_psap_boundaries_objectid", table_name="psap_boundaries")
    op.drop_index("idx_psap_boundaries_state", table_name="psap_boundaries")
    op.drop_index("idx_psap_boundaries_city", table_name="psap_boundaries")
    # Spatial index (GIST) is dropped automatically with the table
    op.drop_table("psap_boundaries")
