"""service refunds and frozen settlements

Revision ID: 038_refunds
Revises: 037_backfill_rewards
Create Date: 2026-06-17
"""
import sqlalchemy as sa
from alembic import op


revision = "038_refunds"
down_revision = "037_backfill_rewards"
branch_labels = None
depends_on = None


def _column_names(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 = set(sa.inspect(bind).get_table_names())

    if "order_refunds" not in tables:
        op.create_table(
            "order_refunds",
            sa.Column("refund_no", sa.String(64), nullable=False),
            sa.Column("user_id", sa.BigInteger(), nullable=False),
            sa.Column("order_id", sa.Integer(), nullable=False),
            sa.Column("refund_type", sa.String(24), nullable=False, comment="full / prorated / no_refund"),
            sa.Column(
                "refund_amount",
                sa.Integer(),
                nullable=False,
                server_default=sa.text("0"),
                comment="Refund amount in cents",
            ),
            sa.Column("status", sa.String(24), nullable=False, server_default=sa.text("'success'")),
            sa.Column("reason", sa.Text(), nullable=True),
            sa.Column("payload_snapshot", sa.JSON(), nullable=True),
            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(["order_id"], ["orders.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("refund_no", name="uq_order_refunds_refund_no"),
        )
        op.create_index("ix_order_refunds_refund_no", "order_refunds", ["refund_no"])
        op.create_index("ix_order_refunds_user_id", "order_refunds", ["user_id"])
        op.create_index("ix_order_refunds_order_id", "order_refunds", ["order_id"])
        op.create_index("ix_order_refunds_refund_type", "order_refunds", ["refund_type"])
        op.create_index("ix_order_refunds_status", "order_refunds", ["status"])
    else:
        indexes = _index_names(bind, "order_refunds")
        for index_name, column in (
            ("ix_order_refunds_refund_no", "refund_no"),
            ("ix_order_refunds_user_id", "user_id"),
            ("ix_order_refunds_order_id", "order_id"),
            ("ix_order_refunds_refund_type", "refund_type"),
            ("ix_order_refunds_status", "status"),
        ):
            if index_name not in indexes:
                op.create_index(index_name, "order_refunds", [column])

    if "agent_settlements" in tables:
        columns = _column_names(bind, "agent_settlements")
        if "frozen_until" not in columns:
            op.add_column(
                "agent_settlements",
                sa.Column("frozen_until", sa.DateTime(timezone=True), nullable=True, comment="Frozen reward release time"),
            )
        if "points_amount" not in columns:
            op.add_column(
                "agent_settlements",
                sa.Column(
                    "points_amount",
                    sa.Integer(),
                    nullable=False,
                    server_default=sa.text("0"),
                    comment="Settlement points amount",
                ),
            )
        if "point_log_id" not in columns:
            op.add_column(
                "agent_settlements",
                sa.Column("point_log_id", sa.Integer(), nullable=True, comment="Credited point log id"),
            )
        if "reversed_at" not in columns:
            op.add_column(
                "agent_settlements",
                sa.Column("reversed_at", sa.DateTime(timezone=True), nullable=True, comment="Reversed time"),
            )


def downgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())

    if "agent_settlements" in tables:
        columns = _column_names(bind, "agent_settlements")
        for column in ("reversed_at", "point_log_id", "points_amount", "frozen_until"):
            if column in columns:
                op.drop_column("agent_settlements", column)

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