import { apiClient } from '@/services/api/client';
import { UserSettings, UpdateSettingsRequest } from '../types/settings';
import { AxiosError } from 'axios';

/**
 * Settings Service
 * T0236: Service frontend pour gérer les paramètres utilisateur
 */

/**
 * Récupère les paramètres utilisateur
 * @param userId ID de l'utilisateur
 * @returns Les paramètres utilisateur
 * @throws Error si la requête échoue
 */
export async function getSettings(userId: string): Promise<UserSettings> {
  try {
    const response = await apiClient.get<UserSettings>(
      `/users/${userId}/settings`,
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError) {
      if (error.response?.status === 401) {
        throw new Error('Unauthorized: Please log in to access settings');
      }
      if (error.response?.status === 403) {
        throw new Error('Forbidden: You cannot access these settings');
      }
      if (error.response?.status === 404) {
        throw new Error('Settings not found');
      }
      const errorMessage =
        error.response?.data?.error ||
        error.message ||
        'Failed to fetch settings';
      throw new Error(errorMessage);
    }
    throw error;
  }
}

/**
 * Met à jour les paramètres utilisateur
 * @param userId ID de l'utilisateur
 * @param settings Les paramètres à mettre à jour
 * @throws Error si la requête échoue
 */
export async function updateSettings(
  _userId: string,
  settings: UpdateSettingsRequest,
): Promise<void> {
  try {
    // Backend endpoint is /users/settings (without userId, uses authenticated user)
    await apiClient.put(`/users/settings`, settings);
  } catch (error) {
    if (error instanceof AxiosError) {
      if (error.response?.status === 400) {
        const errorMessage =
          error.response?.data?.error || 'Invalid settings data';
        throw new Error(errorMessage);
      }
      if (error.response?.status === 401) {
        throw new Error('Unauthorized: Please log in to update settings');
      }
      if (error.response?.status === 403) {
        throw new Error('Forbidden: You cannot update these settings');
      }
      if (error.response?.status === 404) {
        throw new Error('Settings not found');
      }
      const errorMessage =
        error.response?.data?.error ||
        error.message ||
        'Failed to update settings';
      throw new Error(errorMessage);
    }
    throw error;
  }
}
