import { createNocoDBEventsClient } from '~/server/utils/nocodb-events';

export default defineEventHandler(async (event) => {
  try {
    // Try to get next meeting from events
    const eventsClient = createNocoDBEventsClient();
    const now = new Date();
    
    let nextMeeting = null;
    
    try {
      const eventsResponse = await eventsClient.findAll({
        limit: 100  // Increased limit to ensure we get all upcoming events
      });
      
      // Handle different possible response structures
      const eventsList = (eventsResponse as any)?.list || [];
      
      if (eventsList && Array.isArray(eventsList)) {
        // Filter for future meetings and sort by date
        const upcomingMeetings = eventsList
          .filter((event: any) => {
            if (!event.start_datetime) return false;
            const eventDate = new Date(event.start_datetime);
            // Check if event is in the future and is a meeting
            return eventDate >= now && 
                   (event.event_type === 'meeting' || 
                    event.title?.toLowerCase().includes('meeting') ||
                    event.title?.toLowerCase().includes('board'));
          })
          .sort((a: any, b: any) => new Date(a.start_datetime).getTime() - new Date(b.start_datetime).getTime());
        
        if (upcomingMeetings.length > 0) {
          const meeting = upcomingMeetings[0];
          const meetingDate = new Date(meeting.start_datetime);
          
          nextMeeting = {
            id: meeting.Id || meeting.id,
            title: meeting.title || 'Board Meeting',
            date: meetingDate.toLocaleDateString('en-US', { 
              year: 'numeric', 
              month: 'long', 
              day: 'numeric' 
            }),
            time: meetingDate.toLocaleTimeString('en-US', {
              hour: 'numeric',
              minute: '2-digit',
              timeZoneName: 'short'
            }),
            location: meeting.location || 'To be announced',
            description: meeting.description || '',
            // Add additional fields for better UI
            isoDate: meeting.start_datetime,
            endTime: meeting.end_datetime || null,
            eventType: meeting.event_type || 'meeting'
          };
        }
      }
    } catch (error) {
      console.error('[next-meeting] Error fetching events:', error);
    }
    
    // Return appropriate response based on whether we found a meeting
    if (nextMeeting) {
      console.log('[next-meeting] Found upcoming meeting:', nextMeeting.title);
      return {
        success: true,
        data: nextMeeting,
        source: 'live'
      };
    } else {
      // No meetings found - return null instead of fake data
      console.log('[next-meeting] No upcoming meetings found');
      return {
        success: true,
        data: null,
        message: 'No upcoming meetings scheduled',
        source: 'live'
      };
    }

  } catch (error: any) {
    console.error('[next-meeting] Error:', error);
    
    // Return error response instead of fallback data
    return {
      success: false,
      data: null,
      error: 'Unable to fetch meeting information',
      message: 'Please check back later or contact administrator'
    };
  }
});
