import { ICalendarEvent, EntityType, CalendarEventType } from '../types/CalendarTypes';
import { IApiRepository } from './IApiRepository';

interface RawEventData {
  id: string;
  title: string;
  start: string | Date;
  end: string | Date;
  type: string;
  allDay?: boolean;
  bookingId?: string;
  resourceId?: string;
  customerId?: string;
  description?: string;
  recurringId?: string;
  metadata?: Record<string, unknown>;
  [key: string]: unknown;
}

/**
 * MockEventRepository - Loads event data from local JSON file
 *
 * Used for development and testing. Only fetchAll() is implemented.
 */
export class MockEventRepository implements IApiRepository<ICalendarEvent> {
  public readonly entityType: EntityType = 'Event';
  private readonly dataUrl = 'data/mock-events.json';

  /**
   * Fetch all events from mock JSON file
   */
  public async fetchAll(): Promise<ICalendarEvent[]> {
    try {
      const response = await fetch(this.dataUrl);

      if (!response.ok) {
        throw new Error(`Failed to load mock events: ${response.status} ${response.statusText}`);
      }

      const rawData: RawEventData[] = await response.json();
      return this.processCalendarData(rawData);
    } catch (error) {
      console.error('Failed to load event data:', error);
      throw error;
    }
  }

  public async sendCreate(_event: ICalendarEvent): Promise<ICalendarEvent> {
    throw new Error('MockEventRepository does not support sendCreate. Mock data is read-only.');
  }

  public async sendUpdate(_id: string, _updates: Partial<ICalendarEvent>): Promise<ICalendarEvent> {
    throw new Error('MockEventRepository does not support sendUpdate. Mock data is read-only.');
  }

  public async sendDelete(_id: string): Promise<void> {
    throw new Error('MockEventRepository does not support sendDelete. Mock data is read-only.');
  }

  private processCalendarData(data: RawEventData[]): ICalendarEvent[] {
    return data.map((event): ICalendarEvent => {
      // Validate customer event constraints
      if (event.type === 'customer') {
        if (!event.bookingId) console.warn(`Customer event ${event.id} missing bookingId`);
        if (!event.resourceId) console.warn(`Customer event ${event.id} missing resourceId`);
        if (!event.customerId) console.warn(`Customer event ${event.id} missing customerId`);
      }

      return {
        id: event.id,
        title: event.title,
        description: event.description,
        start: new Date(event.start),
        end: new Date(event.end),
        type: event.type as CalendarEventType,
        allDay: event.allDay || false,
        bookingId: event.bookingId,
        resourceId: event.resourceId,
        customerId: event.customerId,
        recurringId: event.recurringId,
        metadata: event.metadata,
        syncStatus: 'synced' as const
      };
    });
  }
}
