// server/api/events/index.get.ts
import { createNocoDBEventsClient, transformEventForCalendar } from '~/server/utils/nocodb-events';
import { createSessionManager } from '~/server/utils/session';
import type { EventFilters } from '~/utils/types';

export default defineEventHandler(async (event) => {
  console.log('[api/events.get] =========================');
  console.log('[api/events.get] GET /api/events - List all events');
  console.log('[api/events.get] Request from:', getClientIP(event));
  
  try {
    const query = getQuery(event) as EventFilters & { 
      limit?: string; 
      offset?: string; 
      calendar_format?: string;
      force?: string;
    };
    
    console.log('[api/events.get] Query parameters:', query);

    // Get user session using the working session manager
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session) {
      console.log('[api/events.get] ❌ No valid session found');
      throw createError({
        statusCode: 401,
        statusMessage: 'Authentication required'
      });
    }

    console.log('[api/events.get] ✅ Valid session found for user:', session.user.email);
    console.log('[api/events.get] User tier:', session.user.tier);

    // Get member record to find the member_id needed for RSVP lookup
    const { getMemberByKeycloakId } = await import('~/server/utils/nocodb');
    const member = await getMemberByKeycloakId(session.user.id);
    const memberIdentifier = member?.member_id || member?.Id || session.user.id;
    
    console.log('[api/events.get] Using member identifier for RSVP lookup:', memberIdentifier);
    console.log('[api/events.get] Member details:', { member_id: member?.member_id, database_id: member?.Id });

    const eventsClient = createNocoDBEventsClient();
    
    // Build filters with user role
    const filters: EventFilters & { limit?: number; offset?: number } = {
      ...query,
      user_role: session.user.tier,
      limit: query.limit ? parseInt(query.limit) : 50,
      offset: query.offset ? parseInt(query.offset) : 0
    };

    // If no date range provided, default to current month + 2 months ahead
    if (!filters.start_date || !filters.end_date) {
      const now = new Date();
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const endDate = new Date(now.getFullYear(), now.getMonth() + 3, 0); // 3 months ahead
      
      filters.start_date = startOfMonth.toISOString();
      filters.end_date = endDate.toISOString();
    }

    console.log('[api/events.get] Fetching events with filters:', filters);

    // Get events from database using the member identifier (not Keycloak ID)
    const response = await eventsClient.findUserEvents(memberIdentifier, filters);
    
    console.log('[api/events.get] ✅ Successfully fetched', response.list.length, 'events');
    
    // Transform for FullCalendar if requested
    if (query.calendar_format === 'true') {
      const calendarEvents = response.list.map(transformEventForCalendar);
      return {
        success: true,
        data: calendarEvents,
        total: response.PageInfo?.totalRows || response.list.length
      };
    }

    return {
      success: true,
      data: response.list,
      total: response.PageInfo?.totalRows || response.list.length,
      pagination: response.PageInfo
    };

  } catch (error: any) {
    console.error('[api/events.get] ❌ Error fetching events:', error);
    
    // Re-throw createError instances
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch events'
    });
  }
});
