import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment.development';
import { User } from '../interfaces/user';
import { firstValueFrom } from 'rxjs';

interface LoginRequest {
  identifiant: string;
  password: string;
}

// Backend returns full user; no token specified in current spec.
type LoginResponse = any;

@Injectable({
  providedIn: 'root',
})
export class Auth {
  private tokenKey = 'pmu_token';
  private userKey = 'pmu_user';

  constructor(private http: HttpClient) {}

  isAuthenticated(): boolean {
    return !!localStorage.getItem(this.tokenKey);
  }

  getUser(): User | null {
    const raw = localStorage.getItem(this.userKey);
    return raw ? (JSON.parse(raw) as User) : null;
  }

  /**
   * Vérifie si l'utilisateur connecté possède un roleId donné.
   */
  hasRoleId(roleId: string): boolean {
    const user = this.getUser();
    if (!user?.roleId) return false;
    return String(user.roleId) === String(roleId);
  }

  /**
   * Vérifie si l'utilisateur possède l'un des rôles attendus (par id).
   */
  hasAnyRoleId(roleIds: string[]): boolean {
    const user = this.getUser();
    if (!user?.roleId) return false;
    return roleIds.map(String).includes(String(user.roleId));
  }

  getToken(): string | null {
    return localStorage.getItem(this.tokenKey);
  }

  setToken(token: string) {
    localStorage.setItem(this.tokenKey, token);
  }

  logout() {
    localStorage.removeItem(this.tokenKey);
    localStorage.removeItem(this.userKey);
  }

  private setSession(token: string, user: User) {
    localStorage.setItem(this.tokenKey, token);
    localStorage.setItem(this.userKey, JSON.stringify(user));
  }

  async login(identifiant: string, password: string) {
    const url = `${environment.apiBaseUrl}/api/v1/auth/login`;
    const body: LoginRequest = { identifiant, password };

    const res = (await firstValueFrom(this.http.post<LoginResponse>(url, body))) as any;

    if (!res) {
      throw new Error('Réponse de connexion invalide');
    }

    // Map backend user to frontend User model
    const user: User = {
      id: String(res.id),
      nom: res.nom,
      prenom: res.prenom,
      identifiant: res.identifiant,
      matriculeAgent: res.matriculeAgent,
      roleId: String(res.roleId),
      restrictionConnexion: !!res.restrictionConnexion,
      restrictionAutomatique: !!res.restrictionAutomatique,
      nombreIpAutorise: res.nombreIpAutorise ?? 0,
      nombreIpAutoAutorise: res.nombreIpAutoAutorise ?? 0,
      statut: res.statut ?? 'ACTIVE',
      derniereConnexion: res.derniereConnexion,
      createdAt: res.createdAt,
      updatedAt: res.updatedAt,
    };

    // Backend spec does not expose a token yet; we set a dummy non-empty token
    // so that authGuard & interceptors keep working.
    const token = (res && (res.token || res.accessToken)) || 'session';
    this.setSession(token, user);
    return true;
  }
}
