import { apiClient } from '@/shared/api/client'
import type { ApiResponse } from '@/shared/types/types'
import type { RealnameStatusValue, RiskStatus, UserStatus } from '@/types/status'

export interface AuthUser {
  id: number
  phone: string
  nickname: string
  avatar_url: string
  realname_status: RealnameStatusValue
  risk_status: RiskStatus
  credit_score: number
  status: UserStatus
}

export interface TokenPair {
  access_token: string
  refresh_token: string
  token_type: string
  expires_in: number
}

export interface LoginData {
  user: AuthUser
  tokens: TokenPair
}

export async function sendSmsCode(phone: string) {
  const { data } = await apiClient.post<ApiResponse<{ phone: string; expires_in: number }>>('/auth/sms/send', {
    phone,
  })
  return data.data
}

export async function loginWithSms(phone: string, code: string) {
  const { data } = await apiClient.post<ApiResponse<LoginData>>('/auth/sms/login', { phone, code })
  return data.data
}

export async function fetchMe() {
  const { data } = await apiClient.get<ApiResponse<AuthUser>>('/me')
  return data.data
}

export async function updateMe(payload: Pick<AuthUser, 'nickname' | 'avatar_url'>) {
  const { data } = await apiClient.put<ApiResponse<AuthUser>>('/me', payload)
  return data.data
}

/** Manually refresh user token (for store to call on app init) */
export async function refreshUserToken(refreshToken: string) {
  const { data } = await apiClient.post<ApiResponse<TokenPair>>('/auth/refresh', {
    refresh_token: refreshToken,
  })
  return data.data
}
