-- 初始化 Cloudpods 基本策略数据
-- 这些策略允许 sysadmin 用户执行管理操作

-- 检查 policy 表是否为空
SET @policy_count = (SELECT COUNT(*) FROM policy);

-- 如果 policy 表为空，插入默认策略
-- 注意：blob 是 MySQL 保留关键字，需要用反引号转义
-- 策略格式需要包含 "policy" 键，并且规则是嵌套字典格式
-- 格式: {"policy": {"service": {"resource": {"action": "result"}}}}
INSERT INTO policy (id, name, type, description, `blob`, scope, domain_id, is_public, created_at, updated_at, deleted)
SELECT 
    LOWER(REPLACE(UUID(), '-', '')),
    'sysadmin-system-policy',
    'sysadmin-system-policy',
    'System admin policy with full permissions',
    '{"policy":{"*":{"*":{"*":"allow"}}}}',
    'system',
    'default',
    1,
    NOW(),
    NOW(),
    0
WHERE @policy_count = 0;

-- 获取刚插入的策略 ID
SET @policy_id = (SELECT id FROM policy WHERE name = 'sysadmin-system-policy' LIMIT 1);

-- 获取 admin 角色 ID
SET @admin_role_id = (SELECT id FROM role WHERE name = 'admin' LIMIT 1);

-- 检查 rolepolicy_tbl 是否已有数据
SET @rp_count = (SELECT COUNT(*) FROM rolepolicy_tbl);

-- 如果 rolepolicy_tbl 为空且策略和角色都存在，插入关联
-- rolepolicy_tbl 主键是 (role_id, project_id, policy_id)，没有 id 列
INSERT INTO rolepolicy_tbl (role_id, project_id, policy_id, created_at, updated_at, deleted, auth)
SELECT 
    @admin_role_id,
    '',
    @policy_id,
    NOW(),
    NOW(),
    0,
    1
WHERE @rp_count = 0 AND @policy_id IS NOT NULL AND @admin_role_id IS NOT NULL;

-- 验证插入结果
SELECT 'Policy count after init:' AS info, COUNT(*) AS count FROM policy;
SELECT 'RolePolicy count after init:' AS info, COUNT(*) AS count FROM rolepolicy_tbl;
