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

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

  // Check authentication
  await requireAuth(event);

  try {
    const query = getQuery(event);
    const { berthId } = query;
    console.log('[get-berth-interested-parties] Request params:', { berthId });

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

    const config = getNocoDbConfiguration();
    const berthsTableId = "mczgos9hr3oa9qc"; // Berth table ID
    
    // The "Interested Parties" field ID needs to be determined
    // For now, let's try to fetch the berth first and see what we get
    const berthUrl = `${config.url}/api/v2/tables/${berthsTableId}/records/${berthId}`;
    console.log('[get-berth-interested-parties] Fetching berth:', berthUrl);
    
    const berth = await $fetch(berthUrl, {
      headers: {
        "xc-token": config.token,
      }
    });
    
    console.log('[get-berth-interested-parties] Berth data:', JSON.stringify(berth, null, 2));
    
    // Check if we have Interested Parties field
    const interestedPartiesField = (berth as any)['Interested Parties'];
    console.log('[get-berth-interested-parties] Interested Parties field:', JSON.stringify(interestedPartiesField, null, 2));
    
    // If we have interested parties, fetch their details
    if (interestedPartiesField && Array.isArray(interestedPartiesField)) {
      // Extract IDs from the interested parties
      const partyIds = interestedPartiesField.map((party: any) => {
        // Handle different possible formats
        if (typeof party === 'number') return party;
        if (typeof party === 'string') return parseInt(party);
        if (party && typeof party === 'object' && party.Id) return party.Id;
        if (party && typeof party === 'object' && party.id) return party.id;
        return null;
      }).filter(id => id !== null);
      
      console.log('[get-berth-interested-parties] Party IDs to fetch:', partyIds);
      
      // Fetch full interest records
      if (partyIds.length > 0) {
        const interestsTableId = "mbs9hjauug4eseo";
        const interestPromises = partyIds.map(id => 
          $fetch(`${config.url}/api/v2/tables/${interestsTableId}/records/${id}`, {
            headers: {
              "xc-token": config.token,
            }
          }).catch(error => {
            console.error(`[get-berth-interested-parties] Failed to fetch interest ${id}:`, error);
            return null;
          })
        );
        
        const interests = await Promise.all(interestPromises);
        const validInterests = interests.filter(i => i !== null);
        
        console.log('[get-berth-interested-parties] Fetched interests:', validInterests.length);
        
        return {
          list: validInterests,
          pageInfo: {
            totalRows: validInterests.length,
            page: 1,
            pageSize: validInterests.length,
            isFirstPage: true,
            isLastPage: true
          }
        };
      }
    }
    
    // Return empty list if no interested parties
    return {
      list: [],
      pageInfo: {
        totalRows: 0,
        page: 1,
        pageSize: 0,
        isFirstPage: true,
        isLastPage: true
      }
    };
    
  } catch (error: any) {
    console.error('[get-berth-interested-parties] Error occurred:', error);
    console.error('[get-berth-interested-parties] Error details:', error instanceof Error ? error.message : 'Unknown error');
    
    // Check if it's a 404 error
    if (error.statusCode === 404 || error.status === 404) {
      // Return empty list instead of throwing error
      return { 
        list: [],
        pageInfo: {
          totalRows: 0,
          page: 1,
          pageSize: 0,
          isFirstPage: true,
          isLastPage: true
        }
      };
    }
    
    throw error;
  }
});
