import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

// @Injectable({
//   providedIn: 'root'
// })
export class ApiService {
  private apiUrl = 'http://localhost:8000/api';
  public controllerName: string;


  
  constructor(private authService: AuthService, private http: HttpClient, controllerName: string) {
    this.controllerName = controllerName;
  }
  
  // Metodo per ottenere l'header Authorization
  private getAuthHeaders(): HttpHeaders {
    const token = localStorage.getItem('nursery_auth_token');//this.authService.getToken();
    
    
    if (!token) {
        return new HttpHeaders();      
    }
    
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }

  private mergeHeaders(base: HttpHeaders, toAdd?: HttpHeaders): HttpHeaders {
        let merged = base;
        toAdd?.keys().forEach(key => {
            const values = toAdd.getAll(key);  // Gestisce multipli valori per header
            values?.forEach(value => {
                merged = merged.append(key, value);
            });
        });
        return merged;
    }
  
  // Esempio di chiamata GET con autenticazione
  get<T>(endpoint: string, params?: HttpParams): Observable<T> {
    const headers = this.getAuthHeaders();
    return this.http.get<T>(`${this.apiUrl}/${endpoint}`, { params, headers });
  }
  
  // Esempio di chiamata POST con autenticazione
  post<T>(endpoint: string, body?: any, header?: HttpHeaders): Observable<T> {
    const headers = this.mergeHeaders(this.getAuthHeaders(), header);
    return this.http.post<T>(`${this.apiUrl}/${endpoint}`, body, { headers });
  }
  
  // Esempio di chiamata PUT con autenticazione
  put<T>(endpoint: string, body?: any, header?: HttpHeaders): Observable<T> {
    const headers = this.mergeHeaders(this.getAuthHeaders(), header);
    return this.http.put<T>(`${this.apiUrl}/${endpoint}`, body, { headers });
  }
  
  // Esempio di chiamata DELETE con autenticazione
  delete<T>(endpoint: string): Observable<T> {
    const headers = this.getAuthHeaders();
    return this.http.delete<T>(`${this.apiUrl}/${endpoint}`, { headers });
  }
}