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();
    const thirtyDaysFromNow = new Date();
    thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30);
    
    let nextMeeting = null;
    
    try {
      const eventsResponse = await eventsClient.findAll({
        limit: 50
      });
      
      // 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);
            return eventDate >= now && 
                   (event.event_type === 'meeting' || event.title?.toLowerCase().includes('meeting'));
          })
          .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,
            description: meeting.description
          };
        }
      }
    } catch (error) {
      console.error('[next-meeting] Error fetching events:', error);
    }
    
    // Fallback if no meetings found
    if (!nextMeeting) {
      nextMeeting = {
        id: null,
        title: 'Board Meeting',
        date: 'January 15, 2025',
        time: '7:00 PM EST',
        location: 'TBD',
        description: 'Monthly board meeting'
      };
    }

    return {
      success: true,
      data: nextMeeting
    };

  } catch (error: any) {
    console.error('[next-meeting] Error:', error);
    
    // Return fallback data
    return {
      success: true,
      data: {
        id: null,
        title: 'Board Meeting',
        date: 'January 15, 2025',
        time: '7:00 PM EST',
        location: 'TBD',
        description: 'Monthly board meeting'
      }
    };
  }
});
