import { apiClient } from '@/services/api/client';
import { AxiosError } from 'axios';

export interface UploadAvatarResponse {
  avatar_url: string;
}

export class AvatarUploadError extends Error {
  constructor(
    message: string,
    public code: 'VALIDATION' | 'NETWORK' | 'SERVER' | 'UNKNOWN',
  ) {
    super(message);
    this.name = 'AvatarUploadError';
  }
}

export async function uploadAvatar(
  userId: string,
  file: File,
  onProgress?: (progress: number) => void,
): Promise<UploadAvatarResponse> {
  const formData = new FormData();
  formData.append('avatar', file);

  try {
    const response = await apiClient.post<UploadAvatarResponse>(
      `/users/${userId}/avatar`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total && onProgress) {
            const progress = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total,
            );
            onProgress(progress);
          }
        },
      },
    );

    return response.data;
  } catch (error: unknown) {
    if (error instanceof AxiosError) {
      if (error.response) {
        // Erreur serveur
        const status = error.response.status;
        if (status === 400) {
          throw new AvatarUploadError(
            error.response.data?.error ||
              'Format ou taille de fichier invalide',
            'VALIDATION',
          );
        } else if (status === 413) {
          throw new AvatarUploadError(
            'Fichier trop volumineux (max 5MB)',
            'VALIDATION',
          );
        } else if (status >= 500) {
          throw new AvatarUploadError(
            'Erreur serveur. Veuillez réessayer.',
            'SERVER',
          );
        } else {
          throw new AvatarUploadError(
            error.response.data?.error || "Erreur lors de l'upload",
            'SERVER',
          );
        }
      } else if (error.request) {
        // Erreur réseau
        throw new AvatarUploadError(
          'Erreur de connexion. Vérifiez votre connexion internet.',
          'NETWORK',
        );
      }
    }
    throw new AvatarUploadError('Erreur inconnue', 'UNKNOWN');
  }
}

export async function deleteAvatar(userId: string): Promise<void> {
  await apiClient.delete(`/users/${userId}/avatar`);
}
