import axios from "axios";
import { getToken } from "hse-auth";

export const SWI_API_BASE =
  (typeof process !== "undefined" && process.env.REACT_APP_SWI_API_URL) ||
  "/api/swi";

function authHeaders() {
  const token = getToken();
  return token ? { Authorization: `Bearer ${token}` } : {};
}

export async function fetchSwiMyAssignments() {
  const { data } = await axios.get(`${SWI_API_BASE}/me/assignments`, {
    headers: authHeaders(),
  });
  return Array.isArray(data) ? data : [];
}

export async function fetchSwiMyLocationDocuments() {
  const { data } = await axios.get(`${SWI_API_BASE}/me/location/documents`, {
    headers: authHeaders(),
  });
  return data && typeof data === "object"
    ? {
        location_name: data.location_name ?? null,
        documents: Array.isArray(data.documents) ? data.documents : [],
      }
    : { location_name: null, documents: [] };
}

export async function fetchSwiDashboardBundle() {
  const [assignments, location] = await Promise.all([
    fetchSwiMyAssignments().catch(() => []),
    fetchSwiMyLocationDocuments().catch(() => ({
      location_name: null,
      documents: [],
    })),
  ]);
  return { assignments, location };
}
