BEGIN;

-- ============================================================================
-- LeAudit Platform Contract Template RBAC Seed
-- 目标：
--   1. 补齐合同模板读写删权限
--   2. 给角色分配模板权限，其中上传/更新/删除仅开放给地区管理员 admin
-- 说明：
--   - 依赖 user_rbac_schema_patch.sql
--   - 依赖合同模板前端路由已存在于 sys_routes
--   - 幂等脚本，可重复执行
-- ============================================================================

WITH route_map AS (
    SELECT id, route_path
    FROM sys_routes
    WHERE deleted_at IS NULL
      AND route_path IN ('/contract-template/list', '/contract-template/search')
)
INSERT INTO permissions (
    permission_key,
    module,
    resource,
    action,
    description,
    display_name,
    permission_type,
    is_system,
    metadata,
    created_at,
    updated_at,
    created_by,
    updated_by,
    parent_id,
    sort_order,
    route_id,
    api_path,
    api_method,
    related_routes
)
SELECT
    seed.permission_key,
    seed.module,
    seed.resource,
    seed.action,
    seed.description,
    seed.display_name,
    'API',
    TRUE,
    NULL::jsonb,
    NOW(),
    NOW(),
    NULL::bigint,
    NULL::bigint,
    NULL::bigint,
    seed.sort_order,
    route_map.id,
    seed.api_path,
    seed.api_method,
    NULL::bigint[]
FROM (
    VALUES
        ('contract_template:list:read',   'contract_template', 'list',   'read', '查看合同模板列表', '查看合同模板列表', '/contract-template/list',   310, '/api/v3/contract-templates',      'GET'),
        ('contract_template:search:read', 'contract_template', 'search', 'read', '搜索合同模板',     '搜索合同模板',     '/contract-template/search', 311, '/api/v3/contract-templates/search','GET'),
        ('contract_template:detail:read', 'contract_template', 'detail', 'read', '查看合同模板详情', '查看合同模板详情', '/contract-template/list',   312, '/api/v3/contract-templates/{id}', 'GET'),
        ('contract_template:create:write', 'contract_template', 'create', 'write', '上传合同模板',   '上传合同模板',     '/contract-template/list',   313, '/api/v3/contract-templates',      'POST'),
        ('contract_template:update:write', 'contract_template', 'update', 'write', '更新合同模板',   '更新合同模板',     '/contract-template/list',   314, '/api/v3/contract-templates/{id}', 'PUT'),
        ('contract_template:delete:delete', 'contract_template', 'delete', 'delete', '删除合同模板', '删除合同模板',     '/contract-template/list',   315, '/api/v3/contract-templates/{id}', 'DELETE')
) AS seed(
    permission_key,
    module,
    resource,
    action,
    description,
    display_name,
    route_path,
    sort_order,
    api_path,
    api_method
)
JOIN route_map ON route_map.route_path = seed.route_path
ON CONFLICT (permission_key) DO UPDATE SET
    module = EXCLUDED.module,
    resource = EXCLUDED.resource,
    action = EXCLUDED.action,
    description = EXCLUDED.description,
    display_name = EXCLUDED.display_name,
    permission_type = EXCLUDED.permission_type,
    is_system = EXCLUDED.is_system,
    route_id = EXCLUDED.route_id,
    api_path = EXCLUDED.api_path,
    api_method = EXCLUDED.api_method,
    sort_order = EXCLUDED.sort_order,
    updated_at = NOW();

WITH role_map AS (
    SELECT id, role_key
    FROM roles
    WHERE role_key IN ('super_admin', 'provincial_admin', 'admin')
),
perm_map AS (
    SELECT id, permission_key
    FROM permissions
    WHERE permission_key LIKE 'contract_template:%'
),
seed(role_key, permission_key, grant_type, data_scope) AS (
    VALUES
        ('super_admin', 'contract_template:list:read', 'GRANT', 'ALL'),
        ('super_admin', 'contract_template:search:read', 'GRANT', 'ALL'),
        ('super_admin', 'contract_template:detail:read', 'GRANT', 'ALL'),

        ('provincial_admin', 'contract_template:list:read', 'GRANT', 'ALL'),
        ('provincial_admin', 'contract_template:search:read', 'GRANT', 'ALL'),
        ('provincial_admin', 'contract_template:detail:read', 'GRANT', 'ALL'),

        ('admin', 'contract_template:list:read', 'GRANT', 'DEPT'),
        ('admin', 'contract_template:search:read', 'GRANT', 'DEPT'),
        ('admin', 'contract_template:detail:read', 'GRANT', 'DEPT'),
        ('admin', 'contract_template:create:write', 'GRANT', 'DEPT'),
        ('admin', 'contract_template:update:write', 'GRANT', 'DEPT'),
        ('admin', 'contract_template:delete:delete', 'GRANT', 'DEPT')
)
INSERT INTO role_permissions (
    role_id,
    permission_id,
    grant_type,
    data_scope,
    created_at,
    updated_at
)
SELECT
    role_map.id,
    perm_map.id,
    seed.grant_type,
    seed.data_scope,
    NOW(),
    NOW()
FROM seed
JOIN role_map ON role_map.role_key = seed.role_key
JOIN perm_map ON perm_map.permission_key = seed.permission_key
ON CONFLICT (role_id, permission_id) DO UPDATE SET
    grant_type = EXCLUDED.grant_type,
    data_scope = EXCLUDED.data_scope,
    updated_at = NOW();

DELETE FROM role_permissions rp
USING roles r, permissions p
WHERE rp.role_id = r.id
  AND rp.permission_id = p.id
  AND r.role_key IN ('super_admin', 'provincial_admin')
  AND p.permission_key IN (
      'contract_template:create:write',
      'contract_template:update:write',
      'contract_template:delete:delete'
  );

COMMIT;
