import API from "@searchkit/api";
 
const api = API({
  connection: {
    host: "<elasticsearch-host>",
    apiKey: "<elasticsearch api-key>", // optional
  },
  search_settings: {
    highlight_attributes: ["title", "actors"],
    search_attributes: ["title", "actors", "query"],
    result_attributes: ["title", "actors", "query"],
    facet_attributes: [
      "type",
      { attribute: "actors", field: "actors.keyword" },
    ],
  },
});
 
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type",
};
 
async function handleOptions(request: Request) {
  return new Response(null, {
    headers: corsHeaders,
  });
}
 
async function handleRequest(event: FetchEvent) {
  // handling cors. Optional depending on your setup
  if (event.request.method === "OPTIONS") {
    // Handle CORS preflight requests
    return handleOptions(event.request);
  }
 
  const body = await event.request.json();
  const results = await api.handleRequest(body);
 
  return new Response(JSON.stringify(results), {
    headers: {
      "content-type": "application/json",
      ...corsHeaders,
    },
  });
}
 
addEventListener("fetch", (event) => {
  return event.respondWith(handleRequest(event));
});