import { ITimeSlot } from '../../types/ScheduleTypes';
import { ResourceService } from '../resources/ResourceService';
import { ScheduleOverrideService } from './ScheduleOverrideService';
import { DateService } from '../../core/DateService';

/**
 * ResourceScheduleService - Get effective schedule for a resource on a date
 *
 * Logic:
 * 1. Check for override on this date
 * 2. Fall back to default schedule for the weekday
 */
export class ResourceScheduleService {
  constructor(
    private resourceService: ResourceService,
    private overrideService: ScheduleOverrideService,
    private dateService: DateService
  ) {}

  /**
   * Get effective schedule for a resource on a specific date
   *
   * @param resourceId - Resource ID
   * @param date - Date string "YYYY-MM-DD"
   * @returns ITimeSlot or null (fri/closed)
   */
  async getScheduleForDate(resourceId: string, date: string): Promise<ITimeSlot | null> {
    // 1. Check for override
    const override = await this.overrideService.getOverride(resourceId, date);
    if (override) {
      return override.schedule;
    }

    // 2. Use default schedule for weekday
    const resource = await this.resourceService.get(resourceId);
    if (!resource || !resource.defaultSchedule) {
      return null;
    }

    const weekDay = this.dateService.getISOWeekDay(date);
    return resource.defaultSchedule[weekDay] || null;
  }

  /**
   * Get schedules for multiple dates
   *
   * @param resourceId - Resource ID
   * @param dates - Array of date strings "YYYY-MM-DD"
   * @returns Map of date -> ITimeSlot | null
   */
  async getSchedulesForDates(resourceId: string, dates: string[]): Promise<Map<string, ITimeSlot | null>> {
    const result = new Map<string, ITimeSlot | null>();

    // Get resource once
    const resource = await this.resourceService.get(resourceId);

    // Get all overrides in date range
    const overrides = dates.length > 0
      ? await this.overrideService.getByDateRange(resourceId, dates[0], dates[dates.length - 1])
      : [];

    // Build override map
    const overrideMap = new Map(overrides.map(o => [o.date, o.schedule]));

    // Resolve each date
    for (const date of dates) {
      // Check override first
      if (overrideMap.has(date)) {
        result.set(date, overrideMap.get(date)!);
        continue;
      }

      // Fall back to default
      if (resource?.defaultSchedule) {
        const weekDay = this.dateService.getISOWeekDay(date);
        result.set(date, resource.defaultSchedule[weekDay] || null);
      } else {
        result.set(date, null);
      }
    }

    return result;
  }
}
