import axios from "axios";
import { getMasterLoginToken, clearMasterStoredAuth } from "hse-auth";
import { getMasterDashboardFilters } from "./masterDashboardFilters.js";

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "",
  timeout: 10000,
});

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)
  );
}

axiosInstance.interceptors.request.use(
  (config) => {
    // config.js paths already include /api/* — avoid /api + /api/sat/... double prefix.
    if (
      config.baseURL &&
      config.url &&
      String(config.url).startsWith("/api/")
    ) {
      config.baseURL = "";
    }
    const token = getMasterLoginToken();
    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) => Promise.reject(error)
);

axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      const url = String(error.config?.url || "");
      const path = url.replace(/^https?:\/\/[^/]+/, "").split("?")[0];
      // Only end the Master session for Master auth/API failures.
      // Personalized dashboard also calls SAT/ORAC APIs; those may reject a
      // Master login JWT without meaning the Master session is invalid.
      const isMasterApi =
        path.startsWith("/api/master/") ||
        path.includes("/api/master/");
      if (isMasterApi) {
        const returnTo = `${window.location.pathname}${window.location.search}`;
        clearMasterStoredAuth();
        const loginUrl =
          returnTo && returnTo !== "/" && !returnTo.startsWith("/login")
            ? `/login?returnTo=${encodeURIComponent(returnTo)}`
            : "/login";
        window.location.href = loginUrl;
      }
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
