import axios from 'axios';
import { getToken, clearStoredAuth, redirectToHseLogin } from 'hse-auth';
import { getMasterDashboardFilters } from './masterDashboardFilters';

// Create axios instance with default config
const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_API_BASE_URL || '',
  timeout: 10000,
});

// API path prefixes that should receive master dashboard location filters (country, site, work area)
const FILTERED_API_PREFIXES = [
  '/api/sat/dashboard/',
  '/api/sat/audits',
  '/api/sat/audit-schedules',
  '/api/sat/activity-log',
  '/api/sat/users',
];

function shouldAddLocationFilter(url) {
  if (!url || typeof url !== 'string') return false;
  const path = url.replace(/^https?:\/\/[^/]+/, '').split('?')[0];
  return FILTERED_API_PREFIXES.some((prefix) => path === prefix || path.startsWith(prefix));
}

// Request interceptor to add JWT token and optional location filters
axiosInstance.interceptors.request.use(
  (config) => {
    // config.js paths already include /api/sat/* — avoid /api + /api/sat/... double prefix.
    if (
      config.baseURL &&
      config.url &&
      String(config.url).startsWith('/api/')
    ) {
      config.baseURL = '';
    }
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    const url = config.url || (config.baseURL && config.url ? config.baseURL + config.url : '');
    const fullUrl = url.startsWith('http') ? url : (config.baseURL || '') + url;
    if (shouldAddLocationFilter(fullUrl)) {
      const f = getMasterDashboardFilters();
      if (f.country_id || f.location_id || f.department_id) {
        config.params = { ...config.params, ...(f.country_id && { country_id: f.country_id }), ...(f.location_id && { location_id: f.location_id }), ...(f.department_id && { department_id: f.department_id }) };
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor to handle token expiration
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      clearStoredAuth();
      redirectToHseLogin();
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;

