CREATE TABLE IF NOT EXISTS qipai_user_admin_profiles (
  tenant_id BIGINT UNSIGNED NOT NULL,
  user_id BIGINT UNSIGNED NOT NULL,
  note VARCHAR(1000) NOT NULL DEFAULT '',
  updated_by BIGINT UNSIGNED NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (tenant_id, user_id),
  CONSTRAINT fk_qipai_user_admin_profiles_tenant FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_user_admin_profiles_user FOREIGN KEY (user_id) REFERENCES qipai_users(id),
  CONSTRAINT fk_qipai_user_admin_profiles_updater FOREIGN KEY (updated_by) REFERENCES qipai_users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_permissions (code, name, category) VALUES
  ('user.read', '查看用户', 'account'),
  ('staff.manage', '管理员工', 'account'),
  ('session.reset', '重置登录会话', 'account');

INSERT IGNORE INTO qipai_role_permissions (tenant_id, role_id, permission_id)
SELECT r.tenant_id, r.id, p.id
FROM qipai_roles r
INNER JOIN qipai_permissions p
  ON (r.code = 'STORE_ADMIN' AND p.code IN ('user.read', 'staff.manage', 'session.reset'))
  OR (r.code IN ('TENANT_ADMIN', 'PLATFORM_ADMIN')
      AND p.code IN ('user.read', 'staff.manage', 'session.reset', 'tenant.manage'));

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026061806', 'm02d_user_management');
