BEGIN;

WITH rules_route AS (
  SELECT id
  FROM sys_routes
  WHERE route_path = '/rules'
    AND deleted_at IS NULL
  LIMIT 1
)
INSERT INTO permissions (
  permission_key,
  module,
  resource,
  action,
  description,
  display_name,
  permission_type,
  is_system,
  metadata,
  created_at,
  updated_at,
  sort_order,
  route_id,
  api_path,
  api_method
)
SELECT *
FROM (
  SELECT 'evaluation_point:list:read', 'evaluation_point', 'list', 'read', '查看评查点列表', '评查点列表', 'API', TRUE, '{}'::jsonb, NOW(), NOW(), 51, (SELECT id FROM rules_route), '/api/v3/evaluation-points', 'GET'
  UNION ALL
  SELECT 'evaluation_point:detail:read', 'evaluation_point', 'detail', 'read', '查看评查点详情', '评查点详情', 'API', TRUE, '{}'::jsonb, NOW(), NOW(), 52, (SELECT id FROM rules_route), '/api/v3/evaluation-points/{id}', 'GET'
  UNION ALL
  SELECT 'evaluation_point:create:write', 'evaluation_point', 'create', 'write', '创建评查点', '创建评查点', 'API', TRUE, '{}'::jsonb, NOW(), NOW(), 53, (SELECT id FROM rules_route), '/api/v3/evaluation-points', 'POST'
  UNION ALL
  SELECT 'evaluation_point:update:write', 'evaluation_point', 'update', 'write', '更新评查点', '更新评查点', 'API', TRUE, '{}'::jsonb, NOW(), NOW(), 54, (SELECT id FROM rules_route), '/api/v3/evaluation-points/{id}', 'PUT'
  UNION ALL
  SELECT 'evaluation_point:delete:delete', 'evaluation_point', 'delete', 'delete', '删除评查点', '删除评查点', 'API', TRUE, '{}'::jsonb, NOW(), NOW(), 55, (SELECT id FROM rules_route), '/api/v3/evaluation-points/{id}', 'DELETE'
) AS seed
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,
  metadata = EXCLUDED.metadata,
  updated_at = NOW(),
  sort_order = EXCLUDED.sort_order,
  route_id = EXCLUDED.route_id,
  api_path = EXCLUDED.api_path,
  api_method = EXCLUDED.api_method;

WITH permission_ids AS (
  SELECT id
  FROM permissions
  WHERE permission_key IN (
    'evaluation_point:list:read',
    'evaluation_point:detail:read',
    'evaluation_point:create:write',
    'evaluation_point:update:write',
    'evaluation_point:delete:delete'
  )
), admin_roles AS (
  SELECT id,
         CASE
           WHEN role_key = 'admin' THEN 'DEPT'
           ELSE 'ALL'
         END AS data_scope
  FROM roles
  WHERE role_key IN ('super_admin', 'provincial_admin', 'admin')
)
INSERT INTO role_permissions (
  role_id,
  permission_id,
  grant_type,
  data_scope,
  created_at,
  updated_at
)
SELECT admin_roles.id, permission_ids.id, 'GRANT', admin_roles.data_scope, NOW(), NOW()
FROM admin_roles
CROSS JOIN permission_ids
ON CONFLICT (role_id, permission_id)
DO UPDATE SET
  grant_type = EXCLUDED.grant_type,
  data_scope = EXCLUDED.data_scope,
  updated_at = NOW();

COMMIT;
