BEGIN;

LOCK TABLE tb_agent_wallet IN ACCESS EXCLUSIVE MODE;

-- 出现信用配置、负余额或信用占用后，旧逻辑已无法安全解释资金事实，禁止回滚。
DO $$
DECLARE
    unsafe_count bigint;
BEGIN
    SELECT COUNT(*)
      INTO unsafe_count
      FROM tb_agent_wallet
     WHERE credit_enabled
        OR credit_limit <> 0
        OR balance < 0
        OR frozen_balance > balance;

    IF unsafe_count > 0 THEN
        RAISE EXCEPTION '已有 % 个钱包产生信用配置或旧逻辑无法解释的资金事实，禁止回滚信用字段，请清偿后再评估', unsafe_count;
    END IF;
END
$$;

DROP INDEX IF EXISTS idx_agent_wallet_main_credit_enabled;

ALTER TABLE tb_agent_wallet
    DROP CONSTRAINT IF EXISTS chk_agent_wallet_credit_config,
    DROP CONSTRAINT IF EXISTS chk_agent_wallet_credit_scope,
    DROP CONSTRAINT IF EXISTS chk_agent_wallet_frozen_nonnegative,
    DROP CONSTRAINT IF EXISTS chk_agent_wallet_arithmetic_range,
    DROP CONSTRAINT IF EXISTS chk_agent_wallet_available_balance,
    DROP CONSTRAINT IF EXISTS chk_agent_wallet_version_nonnegative,
    DROP COLUMN IF EXISTS credit_enabled,
    DROP COLUMN IF EXISTS credit_limit;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
         WHERE conrelid = 'tb_agent_wallet'::regclass
           AND conname = 'chk_agent_wallet_balance'
    ) THEN
        ALTER TABLE tb_agent_wallet
            ADD CONSTRAINT chk_agent_wallet_balance CHECK (balance >= 0);
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint
         WHERE conrelid = 'tb_agent_wallet'::regclass
           AND conname = 'chk_agent_wallet_frozen_balance'
    ) THEN
        ALTER TABLE tb_agent_wallet
            ADD CONSTRAINT chk_agent_wallet_frozen_balance CHECK (
                frozen_balance >= 0 AND frozen_balance <= balance
            );
    END IF;
END
$$;

COMMIT;
