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

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

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

  try {
    const query = getQuery(event);
    const { interestId, linkType } = query;
    console.log('[get-interest-berths] Request params:', { interestId, linkType });

    if (!interestId || !linkType) {
      throw createError({ 
        statusCode: 400, 
        statusMessage: "interestId and linkType are required" 
      });
    }

    const config = getNocoDbConfiguration();
    const interestsTableId = "mbs9hjauug4eseo";
    
    // Determine which link field to use
    let linkFieldId;
    if (linkType === 'berths') {
      linkFieldId = "cj7v7bb9pa5eyo3"; // Berths field
    } else if (linkType === 'recommendations') {
      linkFieldId = "cgthyq2e95ajc52"; // Berth Recommendations field
    } else {
      throw createError({ 
        statusCode: 400, 
        statusMessage: "linkType must be 'berths' or 'recommendations'" 
      });
    }
    
    const url = `${config.url}/api/v2/tables/${interestsTableId}/links/${linkFieldId}/records/${interestId}`;
    console.log('[get-interest-berths] URL:', url);
    
    const result = await $fetch(url, {
      headers: {
        "xc-token": config.token,
      },
      params: {
        limit: 1000,
      },
    });
    
    console.log('[get-interest-berths] Successfully fetched berths for interest:', interestId);
    return result;
  } catch (error: any) {
    console.error('[get-interest-berths] Error occurred:', error);
    console.error('[get-interest-berths] Error details:', error instanceof Error ? error.message : 'Unknown error');
    
    // Check if it's a 404 error
    if (error.statusCode === 404 || error.status === 404) {
      const { interestId } = getQuery(event);
      console.error('[get-interest-berths] Interest not found with ID:', interestId);
      // Return empty list instead of throwing error for newly created interests
      return { list: [] };
    }
    
    throw error;
  }
});
