import { base } from './base';

export interface User {
  id: string;
  email: string;
  name: string | null;
  subscription: string;
}

export interface AuthResponse {
  user: User;
  token: string;
}

export interface RegisterData {
  email: string;
  password: string;
  name: string;
}

export interface LoginData {
  email: string;
  password: string;
}

// Inscription d'un nouvel utilisateur
export const register = async (data: RegisterData): Promise<AuthResponse> => {
  const response = await base.post<AuthResponse>('/auth/register', data);

  if (response.data.token) {
    localStorage.setItem('token', response.data.token);
    localStorage.setItem('user', JSON.stringify(response.data.user));
  }

  return response.data;
};

// Connexion d'un utilisateur existant
export const login = async (data: LoginData): Promise<AuthResponse> => {
  console.log("Tentative de connexion avec:", data.email);
  try {
    const response = await base.post<AuthResponse>('/auth/login', data);
    console.log("Réponse du serveur:", response.data);

    if (response.data.token) {
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', JSON.stringify(response.data.user));
    }

    return response.data;
  } catch (error) {
    console.error("Erreur de connexion:", error);
    throw error;
  }
};

// Déconnexion
export const logout = (): void => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
};

// Récupérer l'utilisateur actuel
export const getCurrentUser = (): User | null => {
  const userStr = localStorage.getItem('user');
  if (userStr) {
    return JSON.parse(userStr);
  }
  return null;
};

// Vérifier si l'utilisateur est connecté
export const isAuthenticated = (): boolean => {
  return !!localStorage.getItem('token');
};

// Récupérer le token
export const getToken = (): string | null => {
  return localStorage.getItem('token');
};