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

export default defineEventHandler(async (event) => {
  console.log('[debug-berth-interested-parties] Request received');

  // Check authentication
  await requireAuth(event);

  try {
    // Get a berth ID from query params
    const query = getQuery(event);
    const berthId = query.id as string;

    if (!berthId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Berth ID is required'
      });
    }

    console.log('[debug-berth-interested-parties] Fetching berth:', berthId);

    // First, get the raw berth data without population
    const config = useRuntimeConfig().nocodb;
    const rawBerthResponse = await $fetch(`${config.url}/api/v2/tables/mczgos9hr3oa9qc/records/${berthId}`, {
      headers: {
        "xc-token": config.token,
      },
      params: {
        fields: '*'
      }
    });

    console.log('[debug-berth-interested-parties] Raw berth data:', JSON.stringify(rawBerthResponse, null, 2));

    // Check the structure of Interested Parties
    const interestedParties = (rawBerthResponse as any)['Interested Parties'];
    console.log('[debug-berth-interested-parties] Raw Interested Parties structure:', JSON.stringify(interestedParties, null, 2));
    console.log('[debug-berth-interested-parties] Interested Parties type:', typeof interestedParties);
    console.log('[debug-berth-interested-parties] Is Array:', Array.isArray(interestedParties));
    
    if (Array.isArray(interestedParties) && interestedParties.length > 0) {
      console.log('[debug-berth-interested-parties] First party:', JSON.stringify(interestedParties[0], null, 2));
      console.log('[debug-berth-interested-parties] First party type:', typeof interestedParties[0]);
      console.log('[debug-berth-interested-parties] First party keys:', Object.keys(interestedParties[0] || {}));
    }

    // Now try the populated version
    const populatedBerth = await getBerthById(berthId);
    console.log('[debug-berth-interested-parties] Populated Interested Parties:', JSON.stringify(populatedBerth['Interested Parties'], null, 2));

    return {
      berthId,
      raw: {
        interestedParties: interestedParties,
        type: typeof interestedParties,
        isArray: Array.isArray(interestedParties),
        length: Array.isArray(interestedParties) ? interestedParties.length : 0,
        firstItem: Array.isArray(interestedParties) && interestedParties.length > 0 ? interestedParties[0] : null,
        firstItemKeys: Array.isArray(interestedParties) && interestedParties.length > 0 && interestedParties[0] ? Object.keys(interestedParties[0]) : []
      },
      populated: {
        interestedParties: populatedBerth['Interested Parties'],
        success: !!populatedBerth['Interested Parties']
      }
    };
  } catch (error: any) {
    console.error('[debug-berth-interested-parties] Error:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to debug berth interested parties'
    });
  }
});
