"""set default full refund limit to three

Revision ID: 058_full_refund_limit_three
Revises: 057_point_center
Create Date: 2026-06-21
"""

import json

import sqlalchemy as sa
from alembic import op


revision = "058_full_refund_limit_three"
down_revision = "057_point_center"
branch_labels = None
depends_on = None


SETTING_KEY = "refund.full_refund_limit"


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


def _normalize(value):
    if isinstance(value, bytes):
        value = value.decode()
    if isinstance(value, str):
        try:
            return json.loads(value)
        except ValueError:
            return value
    return value


def upgrade() -> None:
    bind = op.get_bind()
    if "system_settings" not in _tables(bind):
        return

    row = bind.execute(
        sa.text("SELECT value FROM system_settings WHERE `key` = :key LIMIT 1"),
        {"key": SETTING_KEY},
    ).first()
    if row and _normalize(row[0]) == 2:
        bind.execute(
            sa.text("UPDATE system_settings SET value = :value, updated_at = NOW() WHERE `key` = :key"),
            {"key": SETTING_KEY, "value": json.dumps(3)},
        )


def downgrade() -> None:
    bind = op.get_bind()
    if "system_settings" not in _tables(bind):
        return

    row = bind.execute(
        sa.text("SELECT value FROM system_settings WHERE `key` = :key LIMIT 1"),
        {"key": SETTING_KEY},
    ).first()
    if row and _normalize(row[0]) == 3:
        bind.execute(
            sa.text("UPDATE system_settings SET value = :value, updated_at = NOW() WHERE `key` = :key"),
            {"key": SETTING_KEY, "value": json.dumps(2)},
        )
