"""user refund quota audit logs

Revision ID: 060_user_refund_quota_logs
Revises: 059_user_refund_quota
Create Date: 2026-06-21
"""

import sqlalchemy as sa
from alembic import op


revision = "060_user_refund_quota_logs"
down_revision = "059_user_refund_quota"
branch_labels = None
depends_on = None


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


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 "user_refund_quota_logs" not in tables:
        op.create_table(
            "user_refund_quota_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_extra", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("after_extra", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("before_reset_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("after_reset_at", sa.DateTime(timezone=True), nullable=True),
            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_refund_quota_logs_user_id", "user_refund_quota_logs", ["user_id"])
        op.create_index("ix_user_refund_quota_logs_operator_id", "user_refund_quota_logs", ["operator_id"])
        op.create_index("ix_user_refund_quota_logs_action", "user_refund_quota_logs", ["action"])
    else:
        indexes = _index_names(bind, "user_refund_quota_logs")
        for index_name, column in (
            ("ix_user_refund_quota_logs_user_id", "user_id"),
            ("ix_user_refund_quota_logs_operator_id", "operator_id"),
            ("ix_user_refund_quota_logs_action", "action"),
        ):
            if index_name not in indexes:
                op.create_index(index_name, "user_refund_quota_logs", [column])


def downgrade() -> None:
    bind = op.get_bind()
    if "user_refund_quota_logs" in _tables(bind):
        op.drop_table("user_refund_quota_logs")
