"""extend ticket statuses

Revision ID: 027_ticket_statuses
Revises: 026_tickets
Create Date: 2026-06-14
"""

from alembic import op
import sqlalchemy as sa

revision = "027_ticket_statuses"
down_revision = "026_tickets"
branch_labels = None
depends_on = None

NEW_STATUS_ENUM = "ENUM('open','pending','processing','waiting_user','answered','resolved','closed')"
OLD_STATUS_ENUM = "ENUM('open','pending','answered','closed')"


def upgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "tickets" not in tables:
        return
    op.execute(
        f"ALTER TABLE tickets MODIFY status {NEW_STATUS_ENUM} NOT NULL DEFAULT 'open'"
    )


def downgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "tickets" not in tables:
        return
    op.execute(
        """
        UPDATE tickets
        SET status = CASE
            WHEN status IN ('processing', 'waiting_user') THEN 'answered'
            WHEN status = 'resolved' THEN 'closed'
            ELSE status
        END
        """
    )
    op.execute(
        f"ALTER TABLE tickets MODIFY status {OLD_STATUS_ENUM} NOT NULL DEFAULT 'open'"
    )
