import api from './api'
import type { LoginRequest, RegisterRequest, TokenResponse, User, ProfileUpdatePayload, ChangePasswordPayload, MFASetupResponse, MFAVerifyPayload } from '@/types'

export async function login(data: LoginRequest): Promise<TokenResponse> {
  const response = await api.post<TokenResponse>('/auth/login', data)
  localStorage.setItem('access_token', response.data.access_token)
  localStorage.setItem('refresh_token', response.data.refresh_token)
  return response.data
}

export async function register(data: RegisterRequest): Promise<{ user: User }> {
  const response = await api.post<{ user: User }>('/auth/register', data)
  return response.data
}

export async function logout(): Promise<void> {
  try {
    const refreshToken = localStorage.getItem('refresh_token')
    if (refreshToken) {
      await api.post('/auth/logout', { refresh_token: refreshToken })
    }
  } finally {
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
  }
}

export async function getMe(): Promise<User> {
  const response = await api.get<User>('/auth/me')
  return response.data
}

export async function updateProfile(data: ProfileUpdatePayload): Promise<User> {
  const response = await api.put<User>('/auth/profile', data)
  return response.data
}

export async function uploadAvatar(file: File): Promise<User> {
  const formData = new FormData()
  formData.append('file', file)
  const response = await api.post<User>('/auth/avatar', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return response.data
}

export async function deleteAvatar(): Promise<User> {
  const response = await api.delete<User>('/auth/avatar')
  return response.data
}

export async function changePassword(data: ChangePasswordPayload): Promise<void> {
  await api.post('/auth/change-password', data)
}

export async function setupMFA(): Promise<MFASetupResponse> {
  const response = await api.post<MFASetupResponse>('/auth/mfa/setup')
  return response.data
}

export async function verifyMFA(data: MFAVerifyPayload): Promise<void> {
  await api.post('/auth/mfa/verify', data)
}

export async function disableMFA(password: string): Promise<void> {
  await api.delete('/auth/mfa', { data: { password } })
}
