import { post } from '../utils/request';

/** 后端返回的 auth 结构 (request.ts 已自动解包外层 data) */
interface AuthResponse {
  user: { id: string; phone?: string; nickname?: string; kycLevel: number };
  tokens: { accessToken: string; refreshToken: string; expiresIn: number };
}

/** 前端使用的扁平结构 */
export interface LoginResult {
  accessToken: string;
  refreshToken: string;
  user: { id: string; phone?: string; nickname?: string; kycLevel: number };
}

/** 将后端嵌套结构转为前端扁平结构 */
function toLoginResult(resp: AuthResponse): LoginResult {
  return {
    accessToken: resp.tokens.accessToken,
    refreshToken: resp.tokens.refreshToken,
    user: resp.user,
  };
}

/** SMS 验证码类型 */
export type SmsCodeType = 'REGISTER' | 'LOGIN' | 'RESET_PASSWORD' | 'CHANGE_PHONE';

/** 手机号+验证码登录 */
export async function loginByPhone(phone: string, smsCode: string, deviceInfo?: string) {
  const resp = await post<AuthResponse>('/api/v1/auth/login-phone', { phone, smsCode, ...(deviceInfo ? { deviceInfo } : {}) }, false);
  return toLoginResult(resp);
}

/** 密码登录 */
export async function loginByPassword(identifier: string, password: string) {
  const resp = await post<AuthResponse>('/api/v1/auth/login', { identifier, password }, false);
  return toLoginResult(resp);
}

/** 发送短信验证码 */
export function sendSmsCode(phone: string, type: SmsCodeType = 'LOGIN') {
  return post<{ expiresIn: number }>('/api/v1/auth/sms/send', { phone, type }, false);
}

/** 微信登录 */
export async function loginByWechat(code: string) {
  const resp = await post<AuthResponse>('/api/v1/auth/login-wechat', { code }, false);
  return toLoginResult(resp);
}

/** 注册 */
export async function register(phone: string, smsCode: string, password?: string, nickname?: string) {
  const resp = await post<AuthResponse>('/api/v1/auth/register', {
    phone, smsCode,
    ...(password ? { password } : {}),
    ...(nickname ? { nickname } : {}),
  }, false);
  return toLoginResult(resp);
}

/** 重置密码 */
export function resetPassword(phone: string, smsCode: string, newPassword: string) {
  return post<void>('/api/v1/auth/reset-password', { phone, smsCode, newPassword }, false);
}

/** 登出 */
export function logout() {
  return post<void>('/api/v1/auth/logout');
}
