SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

SET @now_ms = CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED);

CREATE TABLE IF NOT EXISTS admin_databi_kpi_targets (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '后台用户 ID（运营人员）',
  app_code VARCHAR(32) NOT NULL COMMENT '应用编码',
  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '区域 ID，0 表示整个 app',
  period_month CHAR(7) NOT NULL COMMENT '目标月份，格式 YYYY-MM',
  target_usd_minor BIGINT NOT NULL DEFAULT 0 COMMENT '当月充值目标，USD 分',
  daily_target_usd_minor BIGINT NOT NULL DEFAULT 0 COMMENT '当日充值目标，USD 分；0 表示按月目标/自然天数折算',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  UNIQUE KEY uk_admin_databi_kpi_target (user_id, app_code, region_id, period_month),
  KEY idx_admin_databi_kpi_targets_period (period_month, app_code, region_id),
  CONSTRAINT fk_admin_databi_kpi_targets_user FOREIGN KEY (user_id) REFERENCES admin_users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='社交 BI 运营人员充值 KPI 月度目标';

INSERT INTO admin_permissions (name, code, kind, description, created_at_ms, updated_at_ms) VALUES
  ('BI KPI 目标配置', 'databi-kpi:manage', 'button', '允许配置社交 BI 运营人员的充值 KPI 目标', @now_ms, @now_ms),
  ('BI 全员绩效查看', 'databi-kpi:view-all', 'button', '允许查看所有运营人员的 KPI 绩效；无此权限时只能查看自己', @now_ms, @now_ms)
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  kind = VALUES(kind),
  description = VALUES(description),
  updated_at_ms = @now_ms;

INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT admin_role.id, admin_permission.id
FROM admin_roles admin_role
JOIN admin_permissions admin_permission
WHERE admin_role.code = 'platform-admin'
  AND admin_permission.code IN ('databi-kpi:manage', 'databi-kpi:view-all');
