// Centralized Axios instance for all API traffic.
//
// This replaces two separate pieces of the Angular application:
//   1. HttpClient injection inside TripDataService
//   2. The JwtInterceptor class registered through HTTP_INTERCEPTORS
//
// The request interceptor attaches the JWT Bearer token to every
// outgoing request except the authentication endpoints, mirroring the
// isAuthAPI check in the original interceptor. The response
// interceptor centralizes 401 handling: if the server rejects a stale
// or invalid token, the token is dropped from storage so the UI
// immediately reflects the logged-out state.
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { getToken, clearToken } from '../context/token-storage';

export const API_BASE_URL = 'http://localhost:3000/api';

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});

// Request interceptor: attach Authorization header when logged in.
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const isAuthApi =
      config.url === '/login' || config.url === '/register';
    const token = getToken();
    if (token && !isAuthApi) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor: centralized handling of auth failures.
apiClient.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      clearToken();
    }
    return Promise.reject(error);
  }
);

export default apiClient;
