/**
 * Master dashboard location filters (country, site, work area).
 * Stored in localStorage from the master dashboard dropdowns; used to filter data across the app.
 */
const STORAGE_COUNTRY = "masterDashboardCountryId";
const STORAGE_SITE = "masterDashboardLocationId";
const STORAGE_WORKAREA = "masterDashboardDepartmentId";

/**
 * Get current filter values from localStorage.
 * @returns {{ country_id: string, location_id: string, department_id: string }}
 */
export function getMasterDashboardFilters() {
  if (typeof window === "undefined") return { country_id: "", location_id: "", department_id: "" };
  return {
    country_id: localStorage.getItem(STORAGE_COUNTRY) || "",
    location_id: localStorage.getItem(STORAGE_SITE) || "",
    department_id: localStorage.getItem(STORAGE_WORKAREA) || "",
  };
}

/**
 * Build query string for API calls. Only includes non-empty filter values.
 * @returns {string} e.g. "?country_id=1&location_id=5&department_id=2" or ""
 */
export function getMasterDashboardFilterParams() {
  const f = getMasterDashboardFilters();
  const params = new URLSearchParams();
  if (f.country_id) params.set("country_id", f.country_id);
  if (f.location_id) params.set("location_id", f.location_id);
  if (f.department_id) params.set("department_id", f.department_id);
  const q = params.toString();
  return q ? `?${q}` : "";
}

/**
 * Append master dashboard filters to an existing URL (handles existing query string).
 * @param {string} url - e.g. "/api/sat/dashboard/stats" or "/api/sat/audits?limit=10"
 * @returns {string}
 */
export function appendMasterDashboardFilters(url) {
  const f = getMasterDashboardFilters();
  const hasAny = f.country_id || f.location_id || f.department_id;
  if (!hasAny) return url;
  const params = new URLSearchParams(typeof window !== "undefined" && url.includes("?") ? url.split("?")[1] : "");
  if (f.country_id) params.set("country_id", f.country_id);
  if (f.location_id) params.set("location_id", f.location_id);
  if (f.department_id) params.set("department_id", f.department_id);
  const base = url.split("?")[0];
  return `${base}?${params.toString()}`;
}

export { STORAGE_COUNTRY, STORAGE_SITE, STORAGE_WORKAREA };
