import { HttpClient } from '@angular/common/http'; import { computed, Injectable, inject, signal } from '@angular/core'; interface UserResponse { authenticated: boolean; username?: string; email?: string; } export type SessionStatus = 'checking' | 'authenticated' | 'anonymous' | 'signing-out' | 'error'; @Injectable({ providedIn: 'root' }) export class SessionService { private readonly http = inject(HttpClient); readonly status = signal('checking'); readonly isLoggedIn = computed(() => this.status() === 'authenticated'); readonly username = signal(''); readonly email = signal(''); refresh(): void { this.status.set('checking'); this.http.get('/api/user').subscribe({ next: (user) => { this.status.set(user.authenticated ? 'authenticated' : 'anonymous'); this.username.set(user.authenticated ? user.username || 'User' : ''); this.email.set(user.authenticated ? user.email || '' : ''); }, error: () => { this.status.set('error'); this.username.set(''); this.email.set(''); }, }); } logout(): void { if (this.status() === 'signing-out') return; this.status.set('signing-out'); this.http.post('/logout', null, { responseType: 'text' }).subscribe({ next: () => { window.location.href = '/'; }, error: () => { this.status.set('authenticated'); window.alert('Impossible de vous déconnecter. Réessayez.'); }, }); } }