"""Add stages table

Revision ID: 6458e0bc3e9d
Revises: 274385f2a757
Create Date: 2023-04-19 08:59:32.383715

"""

import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ENUM

from alembic import op

# revision identifiers, used by Alembic.
revision: str | None = "6458e0bc3e9d"
down_revision: str | None = "274385f2a757"
branch_labels: str | None = None
depends_on: str | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "stages",
        sa.Column("id", sa.BigInteger(), nullable=False),
        sa.Column("created", sa.DateTime(timezone=True), nullable=False),
        sa.Column("tournament_id", sa.BigInteger(), nullable=False),
        sa.Column("is_active", sa.Boolean(), server_default="false", nullable=False),
        sa.Column(
            "type",
            ENUM(
                "SINGLE_ELIMINATION",
                "SWISS",
                "SWISS_DYNAMIC_TEAMS",
                "ROUND_ROBIN",
                name="stage_type",
                create_type=True,
            ),
            nullable=False,
        ),
        sa.Column(
            "status",
            ENUM(
                "COMPLETED",
                "ACTIVE",
                "INACTIVE",
                name="stage_status",
                create_type=True,
            ),
            nullable=False,
        ),
        sa.ForeignKeyConstraint(
            ["tournament_id"],
            ["tournaments.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_stages_id"), "stages", ["id"], unique=False)

    op.execute(
        """
        INSERT INTO stages (type, tournament_id, created)
        (
            SELECT 'SWISS_DYNAMIC_TEAMS', id, NOW()
            FROM tournaments
        )
        """
    )
    op.add_column("rounds", sa.Column("stage_id", sa.BigInteger(), nullable=True))
    op.execute(
        """
        UPDATE rounds
        SET stage_id = (
            SELECT id
            FROM stages
            WHERE stages.tournament_id = rounds.tournament_id
            LIMIT 1
        )
        """
    )
    op.alter_column(
        "rounds",
        "stage_id",
        existing_type=sa.BigInteger(),
        type_=sa.BigInteger(),
        nullable=False,
    )

    op.drop_constraint("rounds_tournament_id_fkey", "rounds", type_="foreignkey")
    op.create_foreign_key(None, "rounds", "stages", ["stage_id"], ["id"])
    # op.drop_column('rounds', 'tournament_id')
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # op.add_column(
    #     'rounds', sa.Column('tournament_id', sa.BIGINT(), autoincrement=False, nullable=True)
    # )
    # op.drop_constraint('rounds_tournament_id_fkey', 'rounds', type_='foreignkey')
    op.create_foreign_key(
        "rounds_tournament_id_fkey", "rounds", "tournaments", ["tournament_id"], ["id"]
    )
    op.drop_column("rounds", "stage_id")
    op.drop_index(op.f("ix_stages_id"), table_name="stages")
    op.drop_table("stages")
    op.execute("DROP TYPE stage_type")
    # ### end Alembic commands ###
