import { api } from './api';
import { API_ENDPOINTS } from '@/utils/constants';
import {
  LoginCredentials,
  RegisterData,
  AuthResponse,
  User,
  ApiResponse
} from '@/types';

export const authService = {
  // Login with email and password
  login: async (credentials: LoginCredentials): Promise<AuthResponse> => {
    const response = await api.post<any>(
      API_ENDPOINTS.AUTH.LOGIN,
      credentials
    );
    // Le backend retourne {success, token, user} directement
    return {
      token: response.token,
      user: response.user
    };
  },

  // Register new user
  register: async (data: RegisterData): Promise<AuthResponse> => {
    const response = await api.post<any>(
      API_ENDPOINTS.AUTH.REGISTER,
      data
    );
    // Le backend retourne {success, token, user} directement
    return {
      token: response.token,
      user: response.user
    };
  },

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

  // Get current user
  getCurrentUser: async (): Promise<User> => {
    const response = await api.get<any>(API_ENDPOINTS.AUTH.ME);
    // Le backend retourne {success, data: user}
    return response.data || response.user || response;
  },

  // Google OAuth
  googleLogin: async (token: string): Promise<AuthResponse> => {
    const response = await api.post<any>(
      API_ENDPOINTS.AUTH.GOOGLE,
      { token }
    );
    // Le backend retourne {success, token, user} directement
    return {
      token: response.token,
      user: response.user
    };
  },

  // Facebook OAuth
  facebookLogin: async (token: string): Promise<AuthResponse> => {
    const response = await api.post<any>(
      API_ENDPOINTS.AUTH.FACEBOOK,
      { token }
    );
    // Le backend retourne {success, token, user} directement
    return {
      token: response.token,
      user: response.user
    };
  },

  // Verify email
  verifyEmail: async (token: string): Promise<void> => {
    await api.post(API_ENDPOINTS.AUTH.VERIFY_EMAIL, { token });
  },

  // Forgot password
  forgotPassword: async (email: string): Promise<void> => {
    await api.post(API_ENDPOINTS.AUTH.FORGOT_PASSWORD, { email });
  },

  // Reset password
  resetPassword: async (token: string, password: string): Promise<void> => {
    await api.post(API_ENDPOINTS.AUTH.RESET_PASSWORD, { token, password });
  },
};
