import { getBerths, getBerthById } from "../utils/nocodb";
import { requireAuth } from "../utils/auth";

export default defineEventHandler(async (event) => {
  console.log('[test-berth-connection] Testing berth NocoDB connection...');

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

  try {
    // Test fetching all berths
    console.log('[test-berth-connection] Testing getBerths()...');
    const berthsResponse = await getBerths();
    console.log('[test-berth-connection] Berths fetched successfully:', {
      count: berthsResponse.list?.length || 0,
      firstBerth: berthsResponse.list?.[0] ? {
        id: berthsResponse.list[0].Id,
        mooringNumber: berthsResponse.list[0]['Mooring Number'],
        status: berthsResponse.list[0].Status,
        area: berthsResponse.list[0].Area
      } : null
    });

    let testBerth = null;
    if (berthsResponse.list && berthsResponse.list.length > 0) {
      const firstBerthId = berthsResponse.list[0].Id.toString();
      console.log('[test-berth-connection] Testing getBerthById() with ID:', firstBerthId);
      testBerth = await getBerthById(firstBerthId);
      console.log('[test-berth-connection] Individual berth fetched successfully:', {
        id: testBerth.Id,
        mooringNumber: testBerth['Mooring Number'],
        interestedPartiesCount: testBerth['Interested Parties']?.length || 0
      });
    }

    return {
      success: true,
      message: "Berth NocoDB connection test successful",
      data: {
        totalBerths: berthsResponse.list?.length || 0,
        testBerth: testBerth ? {
          id: testBerth.Id,
          mooringNumber: testBerth['Mooring Number'],
          status: testBerth.Status,
          area: testBerth.Area,
          price: testBerth.Price,
          interestedPartiesCount: testBerth['Interested Parties']?.length || 0
        } : null,
        tableId: "mczgos9hr3oa9qc"
      }
    };
  } catch (error) {
    console.error('[test-berth-connection] Error occurred:', error);
    console.error('[test-berth-connection] Error details:', error instanceof Error ? error.message : 'Unknown error');
    
    return {
      success: false,
      message: "Berth NocoDB connection test failed",
      error: error instanceof Error ? error.message : 'Unknown error',
      details: error
    };
  }
});
