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>> {
    // Aggiungi gli header richiesti dal backend
    const token = localStorage.getItem('token');
    
    if (token && !req.url.includes('/login')) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`,
          'REQUEST_METHOD': this.getRequestMethod(req.method) // Aggiungi REQUEST_METHOD
        }
      });
    }
    
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        // Gestisci errori 401 (non autorizzato)
        if (error.status === 401) {
          localStorage.removeItem('token');
          // Reindirizza alla pagina di login
          window.location.href = '/login';
        }
        
        return throwError(() => error);
      })
    );
  }
  
  private getRequestMethod(method: string): string {
    // Mappa i metodi HTTP standard al formato richiesto dal backend
    const methodMap: { [key: string]: string } = {
      'GET': 'GET',
      'POST': 'POST',
      'PUT': 'PUT',
      'DELETE': 'DELETE',
      'PATCH': 'PATCH',
      'HEAD': 'HEAD',
      'OPTIONS': 'OPTIONS'
    };
    
    return methodMap[method] || method;
  }
}