import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { catchError, throwError } from 'rxjs';
import { API_CONFIG } from '../config/api.config';

const backendErrorMessage = (body: unknown): string | null => {
  if (typeof body === 'string') return body.trim() || null;
  if (typeof body !== 'object' || body === null) return null;

  const record = body as Record<string, unknown>;
  for (const key of ['detail', 'message', 'title']) {
    const value = record[key];
    if (typeof value === 'string' && value.trim()) return value.trim();
  }
  return null;
};

const httpErrorMessage = (error: HttpErrorResponse): string => {
  const backendMessage = backendErrorMessage(error.error);
  if (backendMessage) return backendMessage;

  if (error.status > 0) {
    const statusText = error.statusText.trim();
    const meaningfulStatusText = statusText && statusText.toUpperCase() !== 'OK';
    return `HTTP ${error.status}${meaningfulStatusText ? ` ${statusText}` : ''}`;
  }

  return error.message || 'Request failed';
};

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const toastr = inject(ToastrService);
  const authBaseUrl = `${API_CONFIG.baseUrl}${API_CONFIG.endpoints.auth}`;
  const isLoginRequest = req.url.includes(`${authBaseUrl}/login`);
  const isRefreshRequest = req.url.includes(`${authBaseUrl}/refresh`);

  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (!isLoginRequest && !isRefreshRequest && error.status !== 401) {
        const message = httpErrorMessage(error);
        toastr.error(message, 'Request failed');
      }

      return throwError(() => error);
    })
  );
};
