import { withBerthQueue } from '~/server/utils/operation-lock';
import { getNocoDbConfiguration } from '~/server/utils/nocodb';
import { requireAuth } from '~/server/utils/auth';

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

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

  try {
    const body = await readBody(event);
    const { interestId, berthIds } = body;
    console.log('[link-berths] Request body:', { interestId, berthIds });

    if (!interestId || !berthIds || !Array.isArray(berthIds)) {
      throw createError({ 
        statusCode: 400, 
        statusMessage: "interestId and berthIds array are required" 
      });
    }

    // Use queuing system to handle rapid berth selections gracefully
    return await withBerthQueue(interestId, async () => {
      const config = getNocoDbConfiguration();
      const interestsTableId = "mbs9hjauug4eseo";
      const berthsLinkFieldId = "cj7v7bb9pa5eyo3"; // Berths field
      
      // Format the berth IDs for the API
      const berthRecords = berthIds.map(id => ({ Id: id }));
      console.log('[link-berths] Berth records to link:', berthRecords);
      
      const url = `${config.url}/api/v2/tables/${interestsTableId}/links/${berthsLinkFieldId}/records/${interestId}`;
      console.log('[link-berths] URL:', url);
      
      const result = await $fetch(url, {
        method: 'POST',
        headers: {
          "xc-token": config.token,
        },
        body: berthRecords,
      });
      
      console.log('[link-berths] Successfully linked berths to interest:', interestId);
      return result;
    });
    
  } catch (error) {
    console.error('[link-berths] Error occurred:', error);
    console.error('[link-berths] Error details:', error instanceof Error ? error.message : 'Unknown error');
    throw error;
  }
});
