BEGIN;

ALTER TABLE tb_role
    ADD COLUMN IF NOT EXISTS default_credit_enabled boolean NOT NULL DEFAULT false,
    ADD COLUMN IF NOT EXISTS default_credit_limit bigint NOT NULL DEFAULT 0;

COMMENT ON COLUMN tb_role.default_credit_enabled IS '是否启用新建代理默认信用模板；只影响未来新建店铺';
COMMENT ON COLUMN tb_role.default_credit_limit IS '新建代理默认信用额度，单位为分；不追溯修改既有钱包';

ALTER TABLE tb_role
    DROP CONSTRAINT IF EXISTS chk_role_default_credit_config,
    DROP CONSTRAINT IF EXISTS chk_role_default_credit_scope;

ALTER TABLE tb_role
    ADD CONSTRAINT chk_role_default_credit_config CHECK (
        (default_credit_enabled = false AND default_credit_limit = 0) OR
        (default_credit_enabled = true AND default_credit_limit > 0)
    ),
    ADD CONSTRAINT chk_role_default_credit_scope CHECK (
        role_type = 2 OR (default_credit_enabled = false AND default_credit_limit = 0)
    );

COMMENT ON CONSTRAINT chk_role_default_credit_config ON tb_role IS '保证角色默认信用开关和额度组合一致';
COMMENT ON CONSTRAINT chk_role_default_credit_scope ON tb_role IS '保证只有客户角色可以保存新建代理默认信用模板';

INSERT INTO tb_permission (
    created_at, updated_at, creator, updater,
    perm_name, perm_code, perm_type, platform,
    available_for_role_types, url, parent_id, sort, status
)
VALUES (
    NOW(), NOW(), 0, 0,
    '配置角色默认信用', 'role:default-credit:manage', 2, 'web',
    '1', '/api/admin/roles/:id/default-credit', NULL, 0, 1
)
ON CONFLICT (perm_code) WHERE deleted_at IS NULL
DO UPDATE SET
    perm_name = EXCLUDED.perm_name,
    perm_type = EXCLUDED.perm_type,
    platform = EXCLUDED.platform,
    available_for_role_types = EXCLUDED.available_for_role_types,
    url = EXCLUDED.url,
    status = EXCLUDED.status,
    updated_at = NOW();

COMMIT;
