import { deleteInterest, getInterestById } from '~/server/utils/nocodb';
import { requireAuth } from '~/server/utils/auth';

export default defineEventHandler(async (event) => {
  const startTime = Date.now();
  console.log('[delete-interest] =========================');
  console.log('[delete-interest] Request received at:', new Date().toISOString());

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

  try {
    const body = await readBody(event);
    const { id } = body;
    console.log('[delete-interest] Request body:', JSON.stringify(body, null, 2));

    if (!id) {
      console.error('[delete-interest] Missing ID in request');
      console.log('[delete-interest] Duration:', Date.now() - startTime, 'ms');
      throw createError({ statusCode: 400, statusMessage: "ID is required" });
    }

    // Pre-delete verification
    console.log('[delete-interest] Pre-delete verification - checking if record exists...');
    try {
      const existingRecord = await getInterestById(id);
      console.log('[delete-interest] Record found:', {
        id: existingRecord.Id,
        name: existingRecord['Full Name'],
        email: existingRecord['Email Address']
      });
    } catch (verifyError: any) {
      console.error('[delete-interest] Pre-delete verification failed:', verifyError);
      if (verifyError.statusCode === 404 || verifyError.status === 404) {
        console.error('[delete-interest] Record does not exist - cannot delete');
        throw createError({ statusCode: 404, statusMessage: "Record not found" });
      }
    }

    console.log('[delete-interest] Proceeding with deletion for ID:', id);
    const result = await deleteInterest(id);
    console.log('[delete-interest] Delete operation completed successfully');
    console.log('[delete-interest] Result:', JSON.stringify(result, null, 2));
    console.log('[delete-interest] Duration:', Date.now() - startTime, 'ms');
    console.log('[delete-interest] =========================');
    
    return result;
  } catch (error: any) {
    console.error('[delete-interest] =========================');
    console.error('[delete-interest] ERROR OCCURRED');
    console.error('[delete-interest] Error type:', error.constructor.name);
    console.error('[delete-interest] Error message:', error.message);
    console.error('[delete-interest] Error status:', error.statusCode || error.status || 'unknown');
    console.error('[delete-interest] Error stack:', error.stack || 'No stack trace');
    console.error('[delete-interest] Full error object:', JSON.stringify(error, null, 2));
    console.error('[delete-interest] Duration:', Date.now() - startTime, 'ms');
    console.error('[delete-interest] =========================');
    
    if (error.statusCode || error.status) {
      throw error; // Re-throw if it's already a proper error
    } else if (error instanceof Error) {
      throw createError({ statusCode: 500, statusMessage: error.message });
    } else {
      throw createError({
        statusCode: 500,
        statusMessage: "An unexpected error occurred",
      });
    }
  }
});
