export default defineEventHandler(async (event) => {
  const xTagHeader = getRequestHeader(event, "x-tag");
  console.log('[get-berths] Request received with x-tag:', xTagHeader);

  if (!xTagHeader || (xTagHeader !== "094ut234" && xTagHeader !== "pjnvü1230")) {
    console.error('[get-berths] Authentication failed - invalid x-tag:', xTagHeader);
    throw createError({ statusCode: 401, statusMessage: "unauthenticated" });
  }

  try {
    const config = getNocoDbConfiguration();
    const berthsTableId = "mczgos9hr3oa9qc";
    
    console.log('[get-berths] Fetching berths...');
    const berths = await $fetch<{ list: any[] }>(`${config.url}/api/v2/tables/${berthsTableId}/records`, {
      headers: {
        "xc-token": config.token,
      },
      params: {
        limit: 1000,
      },
    });
    
    console.log('[get-berths] Successfully fetched berths, count:', berths.list?.length || 0);
    
    // Sort berths by letter zone and then by number
    if (berths.list && Array.isArray(berths.list)) {
      berths.list.sort((a, b) => {
        const berthA = a['Berth Number'] || '';
        const berthB = b['Berth Number'] || '';
        
        // Extract letter and number parts
        const matchA = berthA.match(/^([A-Za-z]+)(\d+)$/);
        const matchB = berthB.match(/^([A-Za-z]+)(\d+)$/);
        
        if (matchA && matchB) {
          const [, letterA, numberA] = matchA;
          const [, letterB, numberB] = matchB;
          
          // First sort by letter zone
          const letterCompare = letterA.localeCompare(letterB);
          if (letterCompare !== 0) {
            return letterCompare;
          }
          
          // Then sort by number within the same letter zone
          return parseInt(numberA) - parseInt(numberB);
        }
        
        // Fallback to string comparison if pattern doesn't match
        return berthA.localeCompare(berthB);
      });
      
      console.log('[get-berths] Berths sorted by zone and number');
    }
    
    return berths;
  } catch (error) {
    console.error('[get-berths] Error occurred:', error);
    console.error('[get-berths] Error details:', error instanceof Error ? error.message : 'Unknown error');
    throw error;
  }
});
