// Servicios de autenticación

import { apiClient } from "./client"
import type { AuthResponse, User } from "./types"

export const authService = {
  /**
   * Iniciar sesión
   * @param email Email del usuario
   * @param password Contraseña
   * @returns Datos del usuario y token de autenticación
   */
  async login(email: string, password: string): Promise<AuthResponse> {
    const response = await apiClient.post<AuthResponse>("/api/auth/login", {
      email,
      password,
    })

    // Guardar el token en el cliente
    apiClient.setToken(response.token)

    return response
  },

  /**
   * Cerrar sesión
   */
  async logout(): Promise<void> {
    try {
      await apiClient.post("/api/auth/logout")
    } finally {
      // Limpiar el token incluso si la petición falla
      apiClient.setToken(null)
    }
  },

  /**
   * Obtener el token actual
   */
  getToken(): string | null {
    return apiClient.getToken()
  },

  /**
   * Verificar si el usuario está autenticado
   */
  isAuthenticated(): boolean {
    return !!apiClient.getToken()
  },

  /**
   * Obtener datos del usuario actual
   */
  async getMe(): Promise<{ user: User }> {
    return apiClient.get<{ user: User }>("/api/auth/me")
  },

  /**
   * Actualizar perfil del usuario
   */
  async updateProfile(data: { name: string; email: string }): Promise<{ message: string; user: User }> {
    return apiClient.put<{ message: string; user: User }>("/api/auth/profile", data)
  },

  /**
   * Actualizar contraseña
   */
  async updatePassword(data: { current_password: string; password: string; password_confirmation: string }): Promise<{ message: string }> {
    return apiClient.put<{ message: string }>("/api/auth/password", data)
  },
}
