import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, User as FirebaseUser, updateProfile } from 'firebase/auth'; import { doc, setDoc, getDoc } from 'firebase/firestore'; import { auth, db } from '../config/firebase'; import { User } from '../types'; export const authService = { // Inscription async signup(email: string, password: string, displayName?: string): Promise { try { const userCredential = await createUserWithEmailAndPassword(auth, email, password); const user = userCredential.user; // Mettre à jour le profil avec le nom d'affichage if (displayName) { await updateProfile(user, { displayName }); } // Créer le document utilisateur dans Firestore const userData: Omit = { email: user.email!, displayName: displayName || undefined, createdAt: new Date(), sharedWith: [] }; await setDoc(doc(db, 'users', user.uid), userData); return user; } catch (error: any) { throw new Error(this.getErrorMessage(error.code)); } }, // Connexion async login(email: string, password: string): Promise { try { const userCredential = await signInWithEmailAndPassword(auth, email, password); return userCredential.user; } catch (error: any) { throw new Error(this.getErrorMessage(error.code)); } }, // Déconnexion async logout(): Promise { try { await signOut(auth); } catch (error: any) { throw new Error('Erreur lors de la déconnexion'); } }, // Récupérer les données utilisateur depuis Firestore async getUserData(uid: string): Promise { try { const userDoc = await getDoc(doc(db, 'users', uid)); if (userDoc.exists()) { return { uid, ...userDoc.data() } as User; } return null; } catch (error) { console.error('Erreur lors de la récupération des données utilisateur:', error); return null; } }, // Messages d'erreur en français getErrorMessage(errorCode: string): string { switch (errorCode) { case 'auth/email-already-in-use': return 'Cette adresse email est déjà utilisée'; case 'auth/invalid-email': return 'Adresse email invalide'; case 'auth/operation-not-allowed': return 'Opération non autorisée'; case 'auth/weak-password': return 'Le mot de passe doit contenir au moins 6 caractères'; case 'auth/user-disabled': return 'Ce compte a été désactivé'; case 'auth/user-not-found': return 'Aucun compte trouvé avec cette adresse email'; case 'auth/wrong-password': return 'Mot de passe incorrect'; case 'auth/invalid-credential': return 'Identifiants invalides'; default: return 'Une erreur est survenue. Veuillez réessayer.'; } } };