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

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

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

  const query = getQuery(event);
  const { id } = query;
  console.log('[get-interest-by-id] Request for ID:', id);

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

  try {
    console.log('[get-interest-by-id] Fetching interest:', id);
    const interest = await getInterestById(id as string);
    console.log('[get-interest-by-id] Successfully fetched interest:', id);
    
    // Debug documensoID field specifically
    console.log('[get-interest-by-id] DEBUGGING documensoID field:', {
      id: interest.Id,
      documensoID: interest['documensoID'],
      documensoID_type: typeof interest['documensoID'],
      documensoID_raw: JSON.stringify(interest['documensoID']),
      documensoID_exists: 'documensoID' in interest,
      documensoID_truthy: !!interest['documensoID'],
      all_keys: Object.keys(interest).filter(key => key.toLowerCase().includes('documen')),
      signature_links: {
        client: interest['Signature Link Client'],
        cc: interest['Signature Link CC'], 
        developer: interest['Signature Link Developer']
      }
    });
    
    return interest;
  } catch (error: any) {
    console.error('[get-interest-by-id] Error occurred:', error);
    console.error('[get-interest-by-id] Error details:', error instanceof Error ? error.message : 'Unknown error');
    
    // Check if it's a 404 error
    if (error.statusCode === 404 || error.status === 404) {
      console.error('[get-interest-by-id] Interest not found with ID:', id);
      throw createError({ 
        statusCode: 404, 
        statusMessage: `Interest not found with ID: ${id}. It may have been deleted or not yet synchronized.` 
      });
    }
    
    if (error instanceof Error) {
      throw createError({ statusCode: 500, statusMessage: error.message });
    } else {
      throw createError({
        statusCode: 500,
        statusMessage: "An unexpected error occurred",
      });
    }
  }
});
