"""script overlays

Revision ID: 0005_script_overlays
Revises: 0004_drop_legacy_external_overlay_type
Create Date: 2026-05-08
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "0005_script_overlays"
down_revision: Union[str, Sequence[str], None] = "0004_drop_legacy_external_overlay_type"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # 1. Wipe legacy global-type overlay rows and any references to them.
    op.execute(
        "DELETE FROM jobs "
        "WHERE overlay_id IN (SELECT id FROM overlays "
        "WHERE type IN ('l4d2center_maps', 'cedapug_maps'))"
    )
    op.execute(
        "DELETE FROM blueprint_overlays "
        "WHERE overlay_id IN (SELECT id FROM overlays "
        "WHERE type IN ('l4d2center_maps', 'cedapug_maps'))"
    )
    op.execute(
        "DELETE FROM overlay_workshop_items "
        "WHERE overlay_id IN (SELECT id FROM overlays "
        "WHERE type IN ('l4d2center_maps', 'cedapug_maps'))"
    )
    op.execute(
        "DELETE FROM overlays WHERE type IN ('l4d2center_maps', 'cedapug_maps')"
    )

    # 2. Drop globals tables in FK order: item_files -> items -> sources.
    op.drop_index(
        "ix_global_overlay_item_files_item",
        table_name="global_overlay_item_files",
    )
    op.drop_table("global_overlay_item_files")

    op.drop_index(
        "ix_global_overlay_items_source", table_name="global_overlay_items"
    )
    op.drop_table("global_overlay_items")

    op.drop_index(
        "ix_global_overlay_sources_type", table_name="global_overlay_sources"
    )
    op.drop_table("global_overlay_sources")

    # 3. Add new columns on overlays.
    with op.batch_alter_table("overlays") as batch_op:
        batch_op.add_column(
            sa.Column(
                "script",
                sa.Text(),
                nullable=False,
                server_default="",
            )
        )
        batch_op.add_column(
            sa.Column(
                "last_build_status",
                sa.String(length=16),
                nullable=False,
                server_default="",
            )
        )


def downgrade() -> None:
    # data is gone; intentional one-way migration
    pass
