-- permission-v2 stage 1 seed for MySQL 8.0
-- purpose:
-- 1. ensure there is at least one root organization node for user association
-- 2. ensure there is at least one available post for user association
-- 3. bind admin user to an organization and a primary position
--
-- note:
-- 1. the reserved ids below are only for cold-start initialization
-- 2. adjust them before execution if your database already uses the same ids

START TRANSACTION;

INSERT INTO system_dept (
  id, name, parent_id, sort, org_type, path, level, code, phone, email, status,
  creator, create_time, updater, update_time, deleted
)
SELECT
  900000000000000001, '平台根组织', 0, 0, 'company', '/900000000000000001/', 1, 'ROOT',
  NULL, NULL, 0,
  'system', NOW(), 'system', NOW(), b'0'
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM system_dept WHERE parent_id = 0 AND deleted = b'0'
);

INSERT INTO system_post (
  id, name, code, post_type, level_rank, sort, status, remark,
  creator, create_time, updater, update_time, deleted
)
SELECT
  900000000000000101, '系统管理员岗', 'SYS_ADMIN_POST', 'management', 100, 0, 0, 'permission-v2 cold-start seed',
  'system', NOW(), 'system', NOW(), b'0'
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM system_post WHERE deleted = b'0'
);

UPDATE system_users
SET
  dept_id = COALESCE(
    dept_id,
    (SELECT root_dept.id
     FROM (
       SELECT id
       FROM system_dept
       WHERE parent_id = 0 AND deleted = b'0'
       ORDER BY sort ASC, id ASC
       LIMIT 1
     ) root_dept)
  ),
  position_id = COALESCE(
    position_id,
    (SELECT chosen_post.id
     FROM (
       SELECT id
       FROM system_post
       WHERE deleted = b'0'
       ORDER BY sort ASC, id ASC
       LIMIT 1
     ) chosen_post)
  ),
  update_time = NOW(),
  updater = 'system'
WHERE username = 'admin';

COMMIT;

-- verification:
-- SELECT id, username, dept_id, position_id FROM system_users WHERE username = 'admin';
