import { HttpClient } from '@angular/common/http';
import { Injectable, inject, signal } from '@angular/core';
import { map, Observable, tap } from 'rxjs';
import { API_CONFIG } from '../config/api.config';
import { CurrentUserContext } from '../models/context.model';

@Injectable({ providedIn: 'root' })
export class UserContextService {
  private readonly http = inject(HttpClient);
  readonly currentUserContext = signal<CurrentUserContext | null>(null);

  loadCurrentUserProfile(): Observable<CurrentUserContext> {
    return this.http.get<Partial<CurrentUserContext>>(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.currentUserProfile}`).pipe(
      map((response) => ({
        id: response.id?.trim() ?? '',
        email: response.email?.trim() ?? '',
        displayName: response.displayName?.trim() || undefined,
        fullName: response.fullName?.trim() || undefined,
        tenantId: response.tenantId?.trim() || undefined,
        roles: response.roles ?? [],
        defaultLandingPage: response.defaultLandingPage?.trim() || undefined,
      })),
      tap((profile) => {
        this.currentUserContext.set(profile);
      })
    );
  }

  clear(): void {
    this.currentUserContext.set(null);
  }
}