// services/upcomingEventsService.ts
export interface ApiUpcomingEvent {
  id: number;
  title: string;
  description: string;
  schedule: string;
  eventDate?: string;
  isActive: boolean;
  createdDate?: string;
  updatedDate?: string;
}

export interface UpcomingEvent {
  id: string;
  title: string;
  description: string;
  schedule: string;
  eventDate?: string;
}

class UpcomingEventsService {
  private apiBaseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';

  async getActiveUpcomingEvents(): Promise<UpcomingEvent[]> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/upcoming-events/active`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const apiEvents: ApiUpcomingEvent[] = await response.json();
      return this.transformApiEventsToEvents(apiEvents);
    } catch (error) {
      console.error('Error fetching upcoming events:', error);
      return this.getFallbackEvents();
    }
  }

  private transformApiEventsToEvents(apiEvents: ApiUpcomingEvent[]): UpcomingEvent[] {
    return apiEvents.map(apiEvent => ({
      id: apiEvent.id.toString(),
      title: apiEvent.title,
      description: apiEvent.description,
      schedule: apiEvent.schedule,
      eventDate: apiEvent.eventDate
    }));
  }

  private getFallbackEvents(): UpcomingEvent[] {
    return [
      {
        id: '1',
        title: 'Simulation-based Team Drills',
        description: 'Hands-on simulation training designed to improve team coordination and emergency response in high-pressure trauma situations.',
        schedule: 'Q3 2025'
      },
      {
        id: '2',
        title: 'Online Webinar Series',
        description: 'Monthly online sessions covering trauma ethics, young doctor support, and professional development in emergency medicine.',
        schedule: 'Monthly Sessions'
      },
      {
        id: '3',
        title: 'Community Education',
        description: 'Road safety fairs and school education sessions to promote trauma prevention and basic first aid awareness in the community.',
        schedule: 'Ongoing'
      }
    ];
  }
}

export const upcomingEventsService = new UpcomingEventsService();