import api from './axios-instance';
import { API_ENDPOINTS } from '@constants/api-endpoints';
import type {
  LoginCredentials,
  RegisterData,
  AuthResponse,
  User,
} from '@shared/types/entities.types';
import type { ApiResponse } from '@shared/types/api.types';

export const authApi = {
  login: async (credentials: LoginCredentials): Promise<AuthResponse> => {
    const response = await api.post<ApiResponse<AuthResponse>>(
      API_ENDPOINTS.AUTH.LOGIN,
      credentials
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al iniciar sesión');
    }
    return response.data.data;
  },

  register: async (data: RegisterData): Promise<AuthResponse> => {
    const response = await api.post<ApiResponse<AuthResponse>>(
      API_ENDPOINTS.AUTH.REGISTER,
      data
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al registrarse');
    }
    return response.data.data;
  },

  logout: async (): Promise<void> => {
    await api.post(API_ENDPOINTS.AUTH.LOGOUT);
  },

  refresh: async (token: string): Promise<{ token: string }> => {
    const response = await api.post<ApiResponse<{ token: string }>>(
      API_ENDPOINTS.AUTH.REFRESH,
      { token }
    );
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al refrescar token');
    }
    return response.data.data;
  },

  me: async (): Promise<User> => {
    const response = await api.get<ApiResponse<User>>(API_ENDPOINTS.AUTH.ME);
    if (!response.data.success || !response.data.data) {
      throw new Error(response.data.error || 'Error al obtener usuario');
    }
    return response.data.data;
  },

  forgotPassword: async (email: string): Promise<void> => {
    const response = await api.post<ApiResponse>(
      API_ENDPOINTS.AUTH.FORGOT_PASSWORD,
      { email }
    );
    if (!response.data.success) {
      throw new Error(response.data.error || 'Error al enviar correo');
    }
  },

  resetPassword: async (token: string, password: string): Promise<void> => {
    const response = await api.post<ApiResponse>(
      API_ENDPOINTS.AUTH.RESET_PASSWORD,
      { token, password }
    );
    if (!response.data.success) {
      throw new Error(response.data.error || 'Error al restablecer contraseña');
    }
  },
};
