-- 法治日报（法治网）机构用户种子数据
-- 密码统一为 admin123
-- 可重复执行（ON CONFLICT DO NOTHING）

DO $$
DECLARE
  pwd_hash TEXT;
  fazhi_org UUID := 'a0000000-0000-0000-0000-00000000000a';
BEGIN
  -- 获取已有用户的密码hash（admin123）
  SELECT password_hash INTO pwd_hash FROM users WHERE email = 'admin@govai.gov.cn';

  -- 法治日报机构管理员（排序第一位，作为登录页默认账号）
  INSERT INTO organizations (id, name, slug, short_name, description, sort_order, is_active) VALUES
    (fazhi_org, '法治日报', 'fazhiribao', '法治网',
     '法治日报社官方平台，提供法治资讯、政策解读、法律服务与智能应用',
     1, true)
  ON CONFLICT (id) DO NOTHING;

  -- 显式重排所有机构，确保法治日报稳定排在第一位、其余机构顺延（幂等）
  UPDATE organizations SET sort_order = 1  WHERE slug = 'fazhiribao';
  UPDATE organizations SET sort_order = 2  WHERE slug = 'keji';
  UPDATE organizations SET sort_order = 3  WHERE slug = 'gongan';
  UPDATE organizations SET sort_order = 4  WHERE slug = 'fagai';
  UPDATE organizations SET sort_order = 5  WHERE slug = 'jiaoyu';
  UPDATE organizations SET sort_order = 6  WHERE slug = 'renshe';
  UPDATE organizations SET sort_order = 7  WHERE slug = 'caizheng';
  UPDATE organizations SET sort_order = 8  WHERE slug = 'zhujian';
  UPDATE organizations SET sort_order = 9  WHERE slug = 'shijianju';
  UPDATE organizations SET sort_order = 10 WHERE slug = 'lvsuo';

  -- 法治日报机构用户
  INSERT INTO users (id, name, email, password_hash, role, status, org_id) VALUES
    (gen_random_uuid(), '法治日报管理员', 'fazhiribao@govai.gov.cn', pwd_hash, 'admin', 'active', fazhi_org),
    (gen_random_uuid(), '法治网编辑', 'fazhibian@govai.gov.cn', pwd_hash, 'creator', 'active', fazhi_org),
    (gen_random_uuid(), '法治日报记者', 'fazhijizhe@govai.gov.cn', pwd_hash, 'user', 'active', fazhi_org)
  ON CONFLICT (email) DO NOTHING;

END $$;