import { z } from 'zod';
import { UserRoleSchema } from '../enums';

// =============================================================
// Token Exchange  (POST /pac/v1/auth/token)
// =============================================================

/// 可选名字典 — host 换票时一并提供 id → 展示名映射,PAC 不持有主数据。
/// clinics / users 都是 host 侧 id → 显示名(中文)。
///
/// ⚠️ 跟 clinicIds(权限)解耦:dictionary 只管"怎么显示名字",可包含用户
/// 权限范围之外的诊所(如 plan.targetClinicId 落在用户没权限的诊所 — 概率低但存在)。
/// 缺失某 id 时前端回退显示原始 id,不报错。
export const TokenDictionarySchema = z
  .object({
    clinics: z.record(z.string(), z.string()).optional(),
    users: z.record(z.string(), z.string()).optional(),
  })
  .describe('Optional id→displayName dictionary (clinics / users), host-provided');
export type TokenDictionary = z.infer<typeof TokenDictionarySchema>;

// `.strict()` on public-facing input: unknown keys are rejected with a clear
// error rather than silently dropped. Catches host-side typos (`userid` →
// `userId`) before they cause confusing downstream behavior.
export const TokenExchangeUserSchema = z
  .strictObject({
    userId: z.string().min(1).describe('Host-side user id'),
    tenantId: z
      .string()
      .min(1)
      .describe("Host-side tenant id (the host's own customer / org id)"),
    role: UserRoleSchema.describe(
      'PAC role granted to this user. PAC ships three: staff (执行客服) / leader (主管) / admin (后台管理员)',
    ),
    clinicIds: z
      .array(z.string())
      .describe('Clinic ids the user is authorized for'),
    dictionary: TokenDictionarySchema.optional().describe(
      'Optional id→name dictionary for UI display (clinics / users)',
    ),
  })
  .describe('User context for the token being signed');

export const TokenExchangeRequestSchema = z.strictObject({
  appId: z.string().min(1).describe('App id assigned to the host platform'),
  appSecret: z
    .string()
    .min(1)
    .describe('App secret paired with appId. Held server-side only.'),
  user: TokenExchangeUserSchema,
});
export type TokenExchangeRequest = z.infer<typeof TokenExchangeRequestSchema>;

export const TokenExchangeResponseSchema = z.object({
  accessToken: z
    .string()
    .describe('Bearer JWT for subsequent API calls (default 2h TTL)'),
  refreshToken: z
    .string()
    .describe('Refresh JWT — exchange before access token expires'),
  code: z
    .string()
    .describe(
      'One-time exchange code. Pass to the iframe URL; consumed by /auth/exchange-code (default 60s TTL).',
    ),
  expiresIn: z.number().int().describe('Access token lifetime in seconds'),
  codeExpiresIn: z.number().int().describe('One-time code lifetime in seconds'),
});
export type TokenExchangeResponse = z.infer<typeof TokenExchangeResponseSchema>;

// =============================================================
// Exchange Code  (POST /pac/v1/auth/exchange-code)
// =============================================================

export const ExchangeCodeRequestSchema = z.strictObject({
  code: z.string().min(1),
});
export type ExchangeCodeRequest = z.infer<typeof ExchangeCodeRequestSchema>;

export const ExchangeCodeResponseSchema = z.object({
  accessToken: z.string(),
  refreshToken: z.string(),
  expiresIn: z.number().int(),
});
export type ExchangeCodeResponse = z.infer<typeof ExchangeCodeResponseSchema>;

// =============================================================
// Refresh  (POST /pac/v1/auth/refresh)
// =============================================================

export const RefreshTokenRequestSchema = z.strictObject({
  refreshToken: z.string().min(1),
});
export type RefreshTokenRequest = z.infer<typeof RefreshTokenRequestSchema>;

export const RefreshTokenResponseSchema = z.object({
  accessToken: z.string(),
  refreshToken: z.string(),
  expiresIn: z.number().int(),
});
export type RefreshTokenResponse = z.infer<typeof RefreshTokenResponseSchema>;

// =============================================================
// Mock Login  (POST /pac/v1/auth/mock-login) ⭐ 开发 / 试部署用
// =============================================================
//
// 用途:试部署 / 内部演示场景 — 用户访问 /plans 无 token 时,前端弹"快速登录"对话框,
// 后端按 { tenant, role } 预制 user payload 直接产 JWT(跳过 host SSO)
//
// 安全:env 门控 — 只在 NODE_ENV != 'production' 或 PAC_ENABLE_MOCK_LOGIN=true 时启用,
// 生产 host 真接入后置 false / 删该 endpoint
export const MockLoginRequestSchema = z.strictObject({
  /// 租户 slug — 'ruier'(瑞尔) / 'ruitai'(瑞泰),后端映射到 tenant UUID + clinics
  tenant: z.enum(['ruier', 'ruitai']),
  /// PAC 角色 — staff / leader / admin
  role: UserRoleSchema,
  /// 可选:登录为具体客服(externalId,来自 GET /auth/mock-users)。
  /// 给了则用真实客服身份(sub=externalId / 真实姓名 / 该客服所属诊所);不给走通用预制身份。
  userExternalId: z.string().optional(),
});
export type MockLoginRequest = z.infer<typeof MockLoginRequestSchema>;

/// 跟 ExchangeCodeResponse 同形(前端直接 setTokens 用)
export const MockLoginResponseSchema = ExchangeCodeResponseSchema;
export type MockLoginResponse = z.infer<typeof MockLoginResponseSchema>;

// =============================================================
// Mock Users  (GET /pac/v1/auth/mock-users) ⭐ 开发 / 试部署用
// =============================================================
//
// 给"快速登录"对话框的客服花名册(派生自 data/<host>/users.json,回访表口径 · 近 12 月在岗)。
// 选一个客服 → POST /auth/mock-login { tenant, role, userExternalId } 以其真实身份登录。
export const MockUserSchema = z.object({
  externalId: z.string(),
  name: z.string(),
  tenant: z.enum(['ruier', 'ruitai']),
  lastActiveAt: z.string(),
  /// 近 12 月回访量(各诊所合计,排序/展示用)
  contactCount: z.number().int(),
  /// 所属诊所(带中文名,展示用)
  clinics: z.array(z.object({ clinicId: z.string(), name: z.string() })),
});
export type MockUser = z.infer<typeof MockUserSchema>;

export const MockUsersResponseSchema = z.object({ users: z.array(MockUserSchema) });
export type MockUsersResponse = z.infer<typeof MockUsersResponseSchema>;

// =============================================================
// JWT payload — server-only; never sent to host
// =============================================================

export const AccessTokenPayloadSchema = z.object({
  sub: z.string(),
  hostId: z.string(),
  tenantId: z.string(),
  clinicIds: z.array(z.string()),
  /// 集团模型:用户所属源组织命名空间(品牌)。数据范围在患者粒度按它圈本品牌;
  /// 空数组 = 不限品牌(集团级角色 / 单命名空间 host)。缺省视为不限(向后兼容老 token)。
  sourceUnits: z.array(z.string()).optional(),
  role: UserRoleSchema,
  permissions: z.array(z.string()),
  /// 可选名字典(clinics/users id→名),host 换票时带,前端 UI 用于把 UUID 显示成名字。
  /// 体积小(几条诊所);随 JWT 走,F5/refresh 自动带,前端 decodeJwt 即可取。
  dictionary: TokenDictionarySchema.optional(),
  iat: z.number().int(),
  exp: z.number().int(),
});
export type AccessTokenPayload = z.infer<typeof AccessTokenPayloadSchema>;
