BEGIN;

DO $$
DECLARE
    configured_count bigint;
    assigned_count bigint;
BEGIN
    SELECT COUNT(*) INTO configured_count
      FROM tb_role
     WHERE default_credit_enabled OR default_credit_limit <> 0;
    IF configured_count > 0 THEN
        RAISE EXCEPTION '已有 % 个角色配置新建代理默认信用，禁止删除模板字段', configured_count;
    END IF;

    SELECT COUNT(*) INTO assigned_count
      FROM tb_role_permission rp
      JOIN tb_permission p ON p.id = rp.perm_id
     WHERE p.perm_code = 'role:default-credit:manage'
       AND rp.deleted_at IS NULL;
    IF assigned_count > 0 THEN
        RAISE EXCEPTION '角色默认信用权限已分配给 % 个角色，禁止回滚权限定义', assigned_count;
    END IF;
END
$$;

DELETE FROM tb_permission
 WHERE perm_code = 'role:default-credit:manage'
   AND deleted_at IS NULL;

ALTER TABLE tb_role
    DROP CONSTRAINT IF EXISTS chk_role_default_credit_config,
    DROP CONSTRAINT IF EXISTS chk_role_default_credit_scope,
    DROP COLUMN IF EXISTS default_credit_enabled,
    DROP COLUMN IF EXISTS default_credit_limit;

COMMIT;
