import { createInterest } from "../utils/nocodb";
import { requireAuth } from "../utils/auth";

export default defineEventHandler(async (event) => {
  console.log('[create-interest] Request received');

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

  try {
    const body = await readBody(event);
    console.log('[create-interest] Request body fields:', body ? Object.keys(body) : 'none');
    
    if (!body || Object.keys(body).length === 0) {
      console.error('[create-interest] No data provided');
      throw createError({ statusCode: 400, statusMessage: "No data provided" });
    }
    
    console.log('[create-interest] Creating new interest with fields:', Object.keys(body));
    const createdInterest = await createInterest(body);
    console.log('[create-interest] Successfully created interest with ID:', createdInterest.Id);
    
    return createdInterest;
  } catch (error) {
    console.error('[create-interest] Error occurred:', error);
    console.error('[create-interest] Error stack:', error instanceof Error ? error.stack : 'No stack trace');
    
    if (error instanceof Error) {
      throw createError({ statusCode: 500, statusMessage: error.message });
    } else {
      throw createError({
        statusCode: 500,
        statusMessage: "An unexpected error occurred",
      });
    }
  }
});
