import { IBooking, IBookingService, BookingStatus, EntityType } from '../types/CalendarTypes';
import { IApiRepository } from './IApiRepository';

interface RawBookingData {
  id: string;
  customerId: string;
  status: string;
  createdAt: string | Date;
  services: RawBookingService[];
  totalPrice?: number;
  tags?: string[];
  notes?: string;
  [key: string]: unknown;
}

interface RawBookingService {
  serviceId: string;
  serviceName: string;
  baseDuration: number;
  basePrice: number;
  customPrice?: number;
  resourceId: string;
}

/**
 * MockBookingRepository - Loads booking data from local JSON file
 */
export class MockBookingRepository implements IApiRepository<IBooking> {
  public readonly entityType: EntityType = 'Booking';
  private readonly dataUrl = 'data/mock-bookings.json';

  public async fetchAll(): Promise<IBooking[]> {
    try {
      const response = await fetch(this.dataUrl);

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

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

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

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

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

  private processBookingData(data: RawBookingData[]): IBooking[] {
    return data.map((booking): IBooking => ({
      id: booking.id,
      customerId: booking.customerId,
      status: booking.status as BookingStatus,
      createdAt: new Date(booking.createdAt),
      services: booking.services as IBookingService[],
      totalPrice: booking.totalPrice,
      tags: booking.tags,
      notes: booking.notes,
      syncStatus: 'synced' as const
    }));
  }
}
