import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { LanguageService } from '../services/language.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  // Skip interceptor for static assets (translation JSON files)
  if (
    req.url.includes('/assets/') ||
    req.url.endsWith('.json')
  ) {
    return next(req);
  }

  const authService = inject(AuthService);
  const router = inject(Router);
  const langService = inject(LanguageService);
  const token = authService.getToken();

  const headers: Record<string, string> = {
    Accept: 'application/json',
    'Accept-Language': langService.currentLang(),
  };

  if (token) {
    headers['X-Authorization'] = `Bearer ${token}`;
  }

  const authReq = req.clone({ setHeaders: headers });

  return next(authReq).pipe(
    catchError((error: HttpErrorResponse) => {
      // Only redirect on real 401 from server, not on network errors
      if (error.status === 401 && navigator.onLine) {
        authService.removeToken();
        router.navigate(['/login']);
      }
      return throwError(() => error);
    })
  );
};
