import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('token');
    
    if (token && !req.url.includes('/login')) {
      // Clona la richiesta e aggiungi gli header richiesti
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`,
          'REQUEST_METHOD': this.getRequestMethod(req.method)
        }
      });
    }
    
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        // Log dell'errore nel browser (utile per debug)
        console.error('Errore API:', error);
        
        // Gestisci errori 401 (non autorizzato)
        if (error.status === 401) {
          localStorage.removeItem('token');
          window.location.href = '/login';
        }
        
        return throwError(() => error);
      })
    );
  }
  
  private getRequestMethod(method: string): string {
    // Mappa i metodi HTTP standard
    const methodMap: { [key: string]: string } = {
      'GET': 'GET',
      'POST': 'POST',
      'PUT': 'PUT',
      'DELETE': 'DELETE',
      'PATCH': 'PATCH',
      'HEAD': 'HEAD',
      'OPTIONS': 'OPTIONS'
    };
    
    return methodMap[method] || method;
  }
}