import { getInterestById, updateInterest, triggerWebhook } from "../utils/nocodb";
import { requireAuth } from "../utils/auth";

export default defineEventHandler(async (event) => {
  console.log('[eoi-send-to-sales] Request received');

  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);

  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/cCRKsqPB9AHuj4XjFFiPr";
    await triggerWebhook(webhookUrl, webhookPayload);

    // Update the interest to mark that the EOI was sent
    await updateInterest(interestId, {
      "EOI Send to Sales": new Date().toISOString()
    });

    return { success: true, message: "EOI send 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",
      });
    }
  }
});
