import { updateInterest } from '~/server/utils/nocodb';
import { requireAuth } from '~/server/utils/auth';

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

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

  try {
    const body = await readBody(event);
    const { id, data } = body;
    console.log('[update-interest] Request body:', { 
      id, 
      idType: typeof id, 
      dataKeys: data ? Object.keys(data) : 'none' 
    });

    if (!id) {
      console.error('[update-interest] Missing ID in request');
      throw createError({ statusCode: 400, statusMessage: "ID is required" });
    }

    // Ensure ID is a string
    const interestId = String(id);
    console.log('[update-interest] Using ID:', interestId, 'Type:', typeof interestId);

    if (!data || Object.keys(data).length === 0) {
      console.error('[update-interest] No data provided for update');
      throw createError({ statusCode: 400, statusMessage: "No data provided for update" });
    }

    // Remove Id from data if it exists to avoid duplication
    const updateData = { ...data };
    if ('Id' in updateData) {
      delete updateData.Id;
      console.log('[update-interest] Removed Id from update data');
    }

    console.log('[update-interest] Updating interest:', interestId, 'with fields:', Object.keys(updateData));
    const updatedInterest = await updateInterest(interestId, updateData);
    console.log('[update-interest] Successfully updated interest:', interestId);
    
    return updatedInterest;
  } catch (error) {
    console.error('[update-interest] Error occurred:', error);
    console.error('[update-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",
      });
    }
  }
});
