"""Template for new Alembic migration scripts."""

from __future__ import annotations
from sqlalchemy.dialects import postgresql
from geoalchemy2.types import Geometry
import sqlalchemy as sa
from alembic import op

revision = 'e7d4bb03da04'
down_revision = '63d02d67b39e'
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "combined_tracks",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column("name", sa.String(length=128), nullable=True),
        sa.Column("start_station_id", postgresql.UUID(
            as_uuid=True), nullable=False),
        sa.Column("end_station_id", postgresql.UUID(
            as_uuid=True), nullable=False),
        sa.Column("length_meters", sa.Numeric(10, 2), nullable=True),
        sa.Column("max_speed_kph", sa.Integer(), nullable=True),
        sa.Column(
            "is_bidirectional",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("true"),
        ),
        sa.Column(
            "status", sa.String(length=32), nullable=False, server_default="planned"
        ),
        sa.Column(
            "combined_geometry",
            Geometry(geometry_type="LINESTRING", srid=4326),
            nullable=False,
        ),
        sa.Column("constituent_track_ids", sa.Text(), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("timezone('utc', now())"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("timezone('utc', now())"),
            nullable=False,
        ),
        sa.ForeignKeyConstraint(
            ["start_station_id"], ["stations.id"], ondelete="RESTRICT"
        ),
        sa.ForeignKeyConstraint(
            ["end_station_id"], ["stations.id"], ondelete="RESTRICT"
        ),
        sa.UniqueConstraint(
            "start_station_id", "end_station_id", name="uq_combined_tracks_station_pair"
        ),
    )
    op.create_index(
        "ix_combined_tracks_geometry", "combined_tracks", ["combined_geometry"], postgresql_using="gist"
    )


def downgrade() -> None:
    op.drop_index("ix_combined_tracks_geometry", table_name="combined_tracks")
    op.drop_table("combined_tracks")
