import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, Observable, map, tap } from 'rxjs'; import { AuthResponse, UserInfo } from '../models/auth-response'; @Injectable({ providedIn: 'root' }) export class AuthService { private readonly ACCESS_TOKEN_KEY = 'indie_access_token'; private readonly REFRESH_TOKEN_KEY = 'indie_refresh_token'; private readonly USER_KEY = 'indie_user'; private userSubject = new BehaviorSubject(this.loadUser()); user$ = this.userSubject.asObservable(); constructor(private http: HttpClient) {} register(email: string): Observable<{ message: string }> { return this.http.post<{ message: string }>('/api/auth/register', { email }); } login(email: string, password: string): Observable { return this.http.post('/api/auth/login', { email, password }) .pipe(tap(res => this.setSession(res))); } refreshToken(refreshToken: string): Observable { return this.http.post('/api/auth/refresh', { refreshToken }) .pipe(tap(res => this.setSession(res))); } logout(): Observable { return this.http.post('/api/auth/logout', {}) .pipe(tap(() => this.clearSession())); } verifyEmail(token: string): Observable<{ message: string; setupToken?: string }> { return this.http.post<{ message: string; setupToken?: string }>('/api/auth/verify-email', { token }); } resendVerification(email: string): Observable<{ message: string }> { return this.http.post<{ message: string }>('/api/auth/resend-verification', { email }); } setPassword(setupToken: string, password: string, name: string): Observable { return this.http.post('/api/auth/set-password', { setupToken, password, name }); } getAccessToken(): string | null { return localStorage.getItem(this.ACCESS_TOKEN_KEY); } getRefreshToken(): string | null { return localStorage.getItem(this.REFRESH_TOKEN_KEY); } getUser(): UserInfo | null { return this.userSubject.value; } isAuthenticated(): boolean { return !!this.getAccessToken(); } clearSessionForLogout(): void { this.clearSession(); } private setSession(res: AuthResponse): void { localStorage.setItem(this.ACCESS_TOKEN_KEY, res.accessToken); localStorage.setItem(this.REFRESH_TOKEN_KEY, res.refreshToken); localStorage.setItem(this.USER_KEY, JSON.stringify(res.user)); this.userSubject.next(res.user); } private clearSession(): void { localStorage.removeItem(this.ACCESS_TOKEN_KEY); localStorage.removeItem(this.REFRESH_TOKEN_KEY); localStorage.removeItem(this.USER_KEY); this.userSubject.next(null); } private loadUser(): UserInfo | null { const data = localStorage.getItem(this.USER_KEY); return data ? JSON.parse(data) : null; } }