export default defineEventHandler(async (event) => {
  const xTagHeader = getRequestHeader(event, "x-tag");
  console.log('[link-berth-recommendations] Request received with x-tag:', xTagHeader);

  if (!xTagHeader || (xTagHeader !== "094ut234" && xTagHeader !== "pjnvü1230")) {
    console.error('[link-berth-recommendations] Authentication failed - invalid x-tag:', xTagHeader);
    throw createError({ statusCode: 401, statusMessage: "unauthenticated" });
  }

  const body = await readBody(event);
  const { interestId, berthIds } = body;

  if (!interestId || !berthIds || !Array.isArray(berthIds)) {
    throw createError({ 
      statusCode: 400, 
      statusMessage: "interestId and berthIds array are required" 
    });
  }

  const config = getNocoDbConfiguration();
  const interestsTableId = "mbs9hjauug4eseo";
  const berthRecommendationsLinkFieldId = "cgthyq2e95ajc52"; // Berth Recommendations field
  
  // Format the berth IDs for the API
  const berthRecords = berthIds.map(id => ({ Id: id }));
  
  const result = await $fetch(
    `${config.url}/api/v2/tables/${interestsTableId}/links/${berthRecommendationsLinkFieldId}/records/${interestId}`,
    {
      method: 'POST',
      headers: {
        "xc-token": config.token,
      },
      body: berthRecords,
    }
  );
  
  return result;
});
