export default defineEventHandler(async (event) => {
  const xTagHeader = getRequestHeader(event, "x-tag");

  if (!xTagHeader || xTagHeader !== "094ut234") {
    throw createError({ statusCode: 401, statusMessage: "unauthenticated" });
  }

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

    if (!interestId) {
      throw createError({ statusCode: 400, statusMessage: "Interest ID is required" });
    }

    // Get the interest data
    const interest = await getInterestById(interestId);

    // Prepare the webhook payload
    const webhookPayload = {
      "type": "records.after.trigger",
      "id": crypto.randomUUID(), // Generate a random UUID
      "data": {
        "table_id": "mbs9hjauug4eseo",
        "table_name": "Interests",
        "rows": [interest]
      }
    };

    // Trigger the webhook
    const webhookUrl = "https://automation.portnimara.com/api/v1/webhooks/vEWQdpe4CXS24E86tV2Cb";
    await triggerWebhook(webhookUrl, webhookPayload);

    // Update the interest to mark that the request was sent
    await updateInterest(interestId, {
      "Request More Info - To Sales": new Date().toISOString()
    });

    return { success: true, message: "Request more info to sales triggered successfully" };
  } catch (error) {
    if (error instanceof Error) {
      throw createError({ statusCode: 500, statusMessage: error.message });
    } else {
      throw createError({
        statusCode: 500,
        statusMessage: "An unexpected error occurred",
      });
    }
  }
});
