import { get, post } from '@/lib/request'
import { USE_MOCK, delay, mockResponse } from '@/mock'
import { mockUsers } from '@/mock/system/users'

// ==================== Types ====================

export interface SystemUser {
  id: string; account: string; name: string; nickName?: string; phone?: string
  avatar?: SystemOss; avatarId?: string; clientId?: string; tenantId?: string
  createdAt: string; updatedAt: string; roles?: SystemRole[]
}

export interface SystemRole {
  id: string; name: string; code: string; sort?: number
  menus?: SystemMenu[]; createdAt: string; updatedAt: string
}

export interface SystemMenu {
  id: string; name: string; title?: string; code?: string; path?: string
  icon?: string; locale?: string; parentId?: string; permission?: string
  sort?: number; category?: number; children?: SystemMenu[]
  createdAt: string; updatedAt: string
}

export interface SystemOss {
  id: string; name: string; key: string; url: string; suffix?: string
  tag?: string; md5?: string; width?: number; height?: number
  createdAt: string; updatedAt: string
}

export interface SystemClient {
  id: string; clientId: string; name: string; grantType?: string
  activeTimeout?: number; additionalInfo?: string
  createdAt: string; updatedAt: string
}

export interface OperationLog {
  id: string; operatorId: string; operatorName: string
  clientId: string; clientName: string
  method: string; path: string; title: string
  statusCode: number; duration: number // ms
  ip: string; userAgent?: string
  requestBody?: string; responseBody?: string
  createdAt: string
}

export interface CaptchaRes { captcha: string; captchaId: string }
export interface LoginParams { account: string; password: string; captcha: string; captchaId: string }
export interface LoginResponse { token: string; expiresAt: number; user: SystemUser }

// ==================== Auth ====================

export async function getCaptcha() {
  if (USE_MOCK) { await delay(200); return mockResponse({ captcha: 'data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=', captchaId: 'mock-captcha-id' }) }
  return get<{ code: number; data: CaptchaRes; msg: string }>('/auth/captcha')
}

export async function login(data: LoginParams) {
  if (USE_MOCK) { await delay(500); return mockResponse({ token: 'mock-token-xxx', expiresAt: Date.now() + 7200000, user: mockUsers[0] }, '登录成功') }
  return post<{ code: number; data: LoginResponse; msg: string }>('/auth/login', data)
}

export async function logout() {
  if (USE_MOCK) { await delay(100); return mockResponse(null, '已登出') }
  return get<{ code: number; data: null; msg: string }>('/auth/logout')
}

// ==================== 以下在各自文件中实现 ====================
// 这里只导出类型，具体 CRUD 在 api/system/*.ts 子文件中
