"""member commission settlements

Revision ID: 043_member_commission
Revises: 042_refund_resource_status
Create Date: 2026-06-18
"""
import sqlalchemy as sa
from alembic import op


revision = "043_member_commission"
down_revision = "042_refund_resource_status"
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 upgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "agent_settlements" not in tables:
        return
    columns = _column_names(bind, "agent_settlements")
    if "settlement_type" in columns:
        op.alter_column(
            "agent_settlements",
            "settlement_type",
            existing_type=sa.String(16),
            type_=sa.String(32),
            existing_nullable=False,
            existing_comment="agent_profit / agent_subsidy / member_commission",
        )


def downgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "agent_settlements" not in tables:
        return
    columns = _column_names(bind, "agent_settlements")
    if "settlement_type" in columns:
        op.alter_column(
            "agent_settlements",
            "settlement_type",
            existing_type=sa.String(32),
            type_=sa.String(16),
            existing_nullable=False,
            existing_comment="agent_profit / agent_subsidy / member_commission",
        )
