"""user verification quota

Revision ID: 074_user_verification_quota
Revises: 073_ticket_templates_satisfaction
Create Date: 2026-07-08
"""

from alembic import op
import sqlalchemy as sa


revision = "074_user_verification_quota"
down_revision = "073_ticket_templates_satisfaction"
branch_labels = None
depends_on = None


def _table_exists(bind: sa.engine.Connection, table_name: str) -> bool:
    return table_name in set(sa.inspect(bind).get_table_names())


def _index_names(bind: sa.engine.Connection, 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()
    if not _table_exists(bind, "user_verification_quotas"):
        op.create_table(
            "user_verification_quotas",
            sa.Column("user_id", sa.BigInteger(), nullable=False),
            sa.Column("free_used", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("paid_remaining", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("paid_purchased", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("paid_used", sa.Integer(), nullable=False, server_default="0"),
            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.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("user_id", name="uq_user_verification_quotas_user_id"),
        )

    indexes = _index_names(bind, "user_verification_quotas")
    if "ix_user_verification_quotas_user_id" not in indexes:
        op.create_index(
            "ix_user_verification_quotas_user_id",
            "user_verification_quotas",
            ["user_id"],
        )


def downgrade() -> None:
    bind = op.get_bind()
    if _table_exists(bind, "user_verification_quotas"):
        indexes = _index_names(bind, "user_verification_quotas")
        if "ix_user_verification_quotas_user_id" in indexes:
            op.drop_index("ix_user_verification_quotas_user_id", table_name="user_verification_quotas")
        op.drop_table("user_verification_quotas")
