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

interface PermissionResponse {
  roles?: string[];
  permissions?: string[];
  defaultLandingPage?: string;
}

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

  loadPermissions(): Observable<PermissionContext> {
    return this.http.get<PermissionResponse>(``).pipe(
      map((response) => ({
        roles: response.roles ?? [],
        permissions: response.permissions ?? [],
        defaultLandingPage: response.defaultLandingPage?.trim() || undefined,
      })),
      tap((context) => {
        this.permissionContext.set(context);
      })
    );
  }

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