import { inject, Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, catchError, EMPTY, Observable, tap } from 'rxjs'; import { User } from '../model/User'; import { AuthService } from '@service/auth.service'; @Injectable({ providedIn: 'root', }) export class UserService { public currentUserSubject = new BehaviorSubject(null); public currentUser$ = this.currentUserSubject.asObservable(); private http: HttpClient = inject(HttpClient); private authService = inject(AuthService); constructor() { // Initialize with the current user from AuthService if available const currentUser = this.authService.getUser(); if (currentUser) { this.currentUserSubject.next(currentUser); } // Subscribe to auth service user updates this.authService.userSubject.subscribe((user) => { this.currentUserSubject.next(user); }); } public getCurrentUser(): Observable { return this.http.get('/backend/users/me').pipe( catchError(() => EMPTY), tap((user) => this.currentUserSubject.next(user)) ); } public refreshCurrentUser(): void { this.getCurrentUser().subscribe(); this.authService.loadCurrentUser(); } public updateLocalBalance(amount: number): void { const currentUser = this.currentUserSubject.getValue(); if (currentUser) { const updatedUser = { ...currentUser, balance: currentUser.balance + amount, }; this.currentUserSubject.next(updatedUser); } } }