-- =============================================================
-- RVW V4.0 本地测试数据：创建 jtim 期刊租户及测试账号
-- 执行方式：docker cp 此文件 到容器后 psql -f 执行
-- =============================================================

-- 1. 创建 jtim 期刊租户
INSERT INTO platform_schema.tenants (id, name, code, type, status, created_at, updated_at)
VALUES (
  'tenant-jtim-001',
  '中华内科杂志',
  'jtim',
  'HOSPITAL',    -- 暂用 HOSPITAL 类型（期刊类型未来可扩展枚举值 JOURNAL）
  'ACTIVE',
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO NOTHING;

-- 2. 创建 jtim 专属测试用户（密码 bcrypt hash = "Test@1234"）
--    使用 bcrypt hash: $2b$10$hashed_value...  实际用已存在用户代替
--    注意：users.tenant_id 是主租户（用于主站），tenant_members 表决定跨租户访问权限
INSERT INTO platform_schema.users (
  id, phone, password, email, name, tenant_id,
  role, status, is_default_password, is_trial, kb_quota, kb_used, token_version,
  created_at, updated_at
)
VALUES (
  'user-jtim-reviewer-001',
  '13900139001',
  '$2a$10$OzlvWo.N5FKeU9BgBVuZ1e1DPonG7bF/WVO6PVW5d5di.fK7oxUnW',  -- Test@1234
  'jtim-reviewer@test.com',
  '张审稿人',
  'tenant-jtim-001',   -- 主租户 = jtim
  'USER',
  'active',
  false,
  false,
  10,
  0,
  0,
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO NOTHING;

-- 3. 绑定用户到 jtim 租户（tenant_members 表 - 用于 rvwTenantMiddleware 权限校验）
INSERT INTO platform_schema.tenant_members (id, tenant_id, user_id, role, joined_at)
VALUES (
  'member-jtim-reviewer-001',
  'tenant-jtim-001',
  'user-jtim-reviewer-001',
  'USER',
  CURRENT_TIMESTAMP
)
ON CONFLICT (tenant_id, user_id) DO NOTHING;

-- 4. 赋予 RVW 模块权限（user_modules 表）
INSERT INTO platform_schema.user_modules (id, user_id, tenant_id, module_code, is_enabled, created_at, updated_at)
VALUES (
  'umod-jtim-rvw-001',
  'user-jtim-reviewer-001',
  'tenant-jtim-001',
  'RVW',
  true,
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP
)
ON CONFLICT (user_id, tenant_id, module_code) DO NOTHING;

-- 5. 创建 jtim 租户的智能审稿配置（使用系统默认，可后续在 ADMIN 修改）
INSERT INTO platform_schema.tenant_rvw_configs (
  id, tenant_id, data_forensics_level,
  created_at, updated_at
)
VALUES (
  'rvwcfg-jtim-001',
  'tenant-jtim-001',
  'L2',
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP
)
ON CONFLICT DO NOTHING;

-- 6. 验证数据
SELECT
  t.id AS tenant_id,
  t.name AS tenant_name,
  t.code AS tenant_code,
  u.id AS user_id,
  u.name AS user_name,
  u.phone,
  u.email,
  tm.role AS member_role,
  rc.data_forensics_level
FROM platform_schema.tenants t
JOIN platform_schema.users u ON u.tenant_id = t.id
JOIN platform_schema.tenant_members tm ON tm.tenant_id = t.id AND tm.user_id = u.id
LEFT JOIN platform_schema.tenant_rvw_configs rc ON rc.tenant_id = t.id
WHERE t.code = 'jtim';
