import service from '@/utils/request/index'
import type { LoginParams, LoginResponseDto, GetWxSignatureResponseDto } from './types'
import { app_config } from '@/config'

/**
 * 登录 —— 根据 邮箱密码登录
 */
export const loginByEmail = (data: LoginParams) => {
  return service.request<LoginResponseDto>({
    url: '/api/auth/login',
    method: 'POST',
    data,
  })
}

/**
 * 企业微信应用登录
 * 1. 直接拿 code登录
 * 2. 根据 code  + cutEmail + isCodeLogin // 切换账号登录
 */
export const loginByCode = ({
  code,
  isCodeLogin,
  cutEmail,
}: {
  code: string
  isCodeLogin?: number
  cutEmail?: string
}) => {
  return service.request<LoginResponseDto>({
    url: '/api/auth/applicationLogin',
    method: 'POST',
    data: {
      code,
      isCodeLogin,
      cutEmail,
    },
  })
}

/**
 * 生成随机密钥-切换官方账号用
 */
interface GenerateLoginKeyData {
  cutEmail?: string
  timestamp: number
  type: 1 | 2 // 1: 多平台跳转 清除缓存 2: 官方账号切换
  userId: string
}
export const generateLoginKey = (data: GenerateLoginKeyData) => {
  return service.request<string>({
    url: '/api/auth/generateLoginKey',
    method: 'POST',
    data,
  })
}

/**
 * 企业微信获取密钥
 */
export const getWxSignature = (url: string) => {
  const loginType = app_config[import.meta.env.MODE]?.loginType
  return service.request<GetWxSignatureResponseDto>({
    url: '/api/auth/getSign',
    method: 'POST',
    data: {
      url,
      reqType: loginType,
    },
  })
}

/**
 * 获取新的token
 */
export const refreshTokenApi = (refreshToken: string) => {
  return service.request<LoginResponseDto>({
    url: '/api/auth/refreshToken',
    method: 'POST',
    data: {
      refreshToken,
    },
  })
}
