"""invite code history

Revision ID: 062_invite_code_history
Revises: 061_affiliate_reporting_indexes
Create Date: 2026-06-21
"""

import sqlalchemy as sa
from alembic import op


revision = "062_invite_code_history"
down_revision = "061_affiliate_reporting_indexes"
branch_labels = None
depends_on = None


def _tables(bind) -> set[str]:
    return set(sa.inspect(bind).get_table_names())


def _columns(bind, table_name: str) -> set[str]:
    return {column["name"] for column in sa.inspect(bind).get_columns(table_name)}


def _index_names(bind, table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(bind).get_indexes(table_name)}


def upgrade() -> None:
    bind = op.get_bind()
    tables = _tables(bind)

    if "users" in tables and "invite_code_change_count" not in _columns(bind, "users"):
        op.add_column(
            "users",
            sa.Column("invite_code_change_count", sa.Integer(), nullable=False, server_default="0"),
        )

    if "user_invite_codes" not in tables:
        op.create_table(
            "user_invite_codes",
            sa.Column("user_id", sa.BigInteger(), nullable=False),
            sa.Column("code", sa.String(length=32), nullable=False),
            sa.Column("is_current", sa.Boolean(), nullable=False, server_default=sa.false()),
            sa.Column("source", sa.String(length=24), nullable=False, server_default="manual"),
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("code", name="uq_user_invite_codes_code"),
        )
        op.create_index("ix_user_invite_codes_user_id", "user_invite_codes", ["user_id"])
        op.create_index("ix_user_invite_codes_code", "user_invite_codes", ["code"])
        op.create_index("ix_user_invite_codes_is_current", "user_invite_codes", ["is_current"])
    else:
        indexes = _index_names(bind, "user_invite_codes")
        if "ix_user_invite_codes_user_id" not in indexes:
            op.create_index("ix_user_invite_codes_user_id", "user_invite_codes", ["user_id"])
        if "ix_user_invite_codes_code" not in indexes:
            op.create_index("ix_user_invite_codes_code", "user_invite_codes", ["code"])
        if "ix_user_invite_codes_is_current" not in indexes:
            op.create_index("ix_user_invite_codes_is_current", "user_invite_codes", ["is_current"])

    if "users" in tables:
        op.execute(
            """
            INSERT IGNORE INTO user_invite_codes (user_id, code, is_current, source, created_at, updated_at)
            SELECT id, UPPER(invite_code), 1, 'backfill', NOW(), NOW()
            FROM users
            WHERE invite_code IS NOT NULL AND invite_code <> ''
            """
        )

    if "user_agents" in tables:
        op.execute(
            """
            INSERT IGNORE INTO user_invite_codes (user_id, code, is_current, source, created_at, updated_at)
            SELECT user_id, UPPER(invite_code), 0, 'agent_legacy', NOW(), NOW()
            FROM user_agents
            WHERE invite_code IS NOT NULL AND invite_code <> ''
            """
        )


def downgrade() -> None:
    bind = op.get_bind()
    tables = _tables(bind)

    if "user_invite_codes" in tables:
        op.drop_table("user_invite_codes")

    if "users" in tables and "invite_code_change_count" in _columns(bind, "users"):
        op.drop_column("users", "invite_code_change_count")
