"""invite code admin quota

Revision ID: 063_invite_code_admin_quota
Revises: 062_invite_code_history
Create Date: 2026-06-21
"""

import sqlalchemy as sa
from alembic import op


revision = "063_invite_code_admin_quota"
down_revision = "062_invite_code_history"
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_extra" not in _columns(bind, "users"):
        op.add_column(
            "users",
            sa.Column("invite_code_change_extra", sa.Integer(), nullable=False, server_default="0"),
        )

    if "user_invite_code_logs" not in tables:
        op.create_table(
            "user_invite_code_logs",
            sa.Column("user_id", sa.BigInteger(), nullable=False),
            sa.Column("operator_id", sa.BigInteger(), nullable=True),
            sa.Column("action", sa.String(length=24), nullable=False),
            sa.Column("count", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("before_used", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("after_used", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("before_extra", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("after_extra", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("reason", sa.Text(), nullable=False),
            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"),
        )
        op.create_index("ix_user_invite_code_logs_user_id", "user_invite_code_logs", ["user_id"])
        op.create_index("ix_user_invite_code_logs_operator_id", "user_invite_code_logs", ["operator_id"])
        op.create_index("ix_user_invite_code_logs_action", "user_invite_code_logs", ["action"])
    else:
        indexes = _index_names(bind, "user_invite_code_logs")
        for index_name, column in (
            ("ix_user_invite_code_logs_user_id", "user_id"),
            ("ix_user_invite_code_logs_operator_id", "operator_id"),
            ("ix_user_invite_code_logs_action", "action"),
        ):
            if index_name not in indexes:
                op.create_index(index_name, "user_invite_code_logs", [column])


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

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

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