import { appConfig } from "@/config/env";
import store from "@/store";

const buildHeaders = (headers = {}) => {
  return {
    "Content-Type": "application/json",
    ...headers,
  };
};

const resolveAccessToken = async () => {
  try {
    return await store.state.directus.client.getToken();
  } catch (error) {
    return null;
  }
};

export const fastapiRequest = async (path, options = {}) => {
  const accessToken = await resolveAccessToken();
  const authHeaders = accessToken
    ? {
        Authorization: `Bearer ${accessToken}`,
      }
    : {};

  const response = await fetch(`${appConfig.mktapiBaseUrl}${path}`, {
    ...options,
    headers: buildHeaders({
      ...authHeaders,
      ...options.headers,
    }),
  });

  const contentType = response.headers.get("content-type") || "";
  const payload = contentType.includes("application/json")
    ? await response.json()
    : await response.text();

  if (!response.ok) {
    throw new Error(
      payload?.detail || payload?.message || `FastAPI request failed: ${path}`
    );
  }

  return payload;
};

export default {
  request: fastapiRequest,
};
