import apiClient from './client'
import type {
  LoginRequest,
  TokenResponse,
  TOTPSetupResponse,
  TOTPStatusResponse,
  UserResponse,
} from '@/types/api.types'

export const authApi = {
  /**
   * Login con email + password (+ opzionale codice TOTP).
   */
  login: (data: LoginRequest) =>
    apiClient.post<TokenResponse>('/auth/login', data).then((r) => r.data),

  /**
   * Rinnova access token con refresh token.
   */
  refresh: (refreshToken: string) =>
    apiClient
      .post<TokenResponse>('/auth/refresh', { refresh_token: refreshToken })
      .then((r) => r.data),

  /**
   * Revoca il refresh token (logout).
   */
  logout: (refreshToken: string) =>
    apiClient.post('/auth/logout', { refresh_token: refreshToken }),

  /**
   * Recupera l'utente corrente autenticato.
   */
  me: () => apiClient.get<UserResponse>('/auth/me').then((r) => r.data),

  /**
   * Setup 2FA TOTP: restituisce QR code e segreto.
   */
  totpSetup: () =>
    apiClient.post<TOTPSetupResponse>('/auth/totp/setup').then((r) => r.data),

  /**
   * Verifica e attiva il TOTP.
   */
  totpVerify: (totp_code: string) =>
    apiClient
      .post<TOTPStatusResponse>('/auth/totp/verify', { totp_code })
      .then((r) => r.data),

  /**
   * Disabilita il TOTP.
   */
  totpDisable: () =>
    apiClient.post<TOTPStatusResponse>('/auth/totp/disable').then((r) => r.data),

  /**
   * Cambio password utente corrente.
   */
  changePassword: (current_password: string, new_password: string) =>
    apiClient.post('/auth/change-password', { current_password, new_password }),
}
