SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- App 可见范围与财务区域范围分开保存。已有用户保持历史全 App 行为；新建用户默认无 App，
-- 避免创建用户成功但后续授权保存失败时短暂获得全量 App。
ALTER TABLE admin_users
  ADD COLUMN app_scope_mode VARCHAR(16) NOT NULL DEFAULT 'all' COMMENT '主后台 App 范围：all/selected/none' AFTER status;

ALTER TABLE admin_users
  ALTER COLUMN app_scope_mode SET DEFAULT 'none';

CREATE TABLE admin_user_app_scopes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '后台用户 ID',
  app_code VARCHAR(32) NOT NULL COMMENT '允许在主后台切换的 App 编码',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  UNIQUE KEY uk_admin_user_app_scope (user_id, app_code),
  KEY idx_admin_user_app_scopes_user (user_id),
  KEY idx_admin_user_app_scopes_app (app_code),
  CONSTRAINT fk_admin_user_app_scopes_user FOREIGN KEY (user_id) REFERENCES admin_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='后台用户主站 App 可见范围';
