import { apiClient } from './apiClient'
import { logger } from '../utils/logger'

interface AuthResponse {
  access_token: string
  expires_at: string
}

export interface AuthLoginPayload {
  username: string
  password: string
}

export interface AuthRegisterPayload {
  email: string
  username: string
  password: string
  name: string
  company_name: string
  cnpj: string
}

export interface ForgotPasswordPayload {
  email: string
}

export interface ResetPasswordPayload {
  token: string
  password: string
}

export const authService = {
  login: async (payload: AuthLoginPayload) => {
    logger.info('🔐 [authService] Making request to /v1/auth/login with:', payload)
    const data = await apiClient.post<AuthResponse>('/v1/auth/login', payload)
    logger.info('🔐 [authService] Response data:', data)
    return { token: data.access_token, expiresAt: data.expires_at }
  },
  logout: async () => {
    await apiClient.post('/v1/auth/logout')
  },
  register: async (payload: AuthRegisterPayload) => {
    logger.info('🔐 [authService] Making request to /v1/auth/register with:', { ...payload, password: '***' })
    const data = await apiClient.post<AuthResponse>('/v1/auth/register', payload)
    logger.info('🔐 [authService] Register response received')
    return { token: data.access_token, expiresAt: data.expires_at }
  },
  forgotPassword: async (payload: ForgotPasswordPayload) => {
    logger.info('🔐 [authService] Making request to /v1/auth/forgot-password with:', payload)
    const data = await apiClient.post<{ message: string }>('/v1/auth/forgot-password', payload)
    logger.info('🔐 [authService] Forgot password response:', data)
    return data
  },
  resetPassword: async (payload: ResetPasswordPayload) => {
    logger.info('🔐 [authService] Making request to /v1/auth/reset-password')
    const data = await apiClient.post<AuthResponse>('/v1/auth/reset-password', payload)
    logger.info('🔐 [authService] Reset password response received')
    return { token: data.access_token, expiresAt: data.expires_at }
  }
}
