import { date, patterns, type ValidationRule } from "quasar";
import type { Shift } from "src/modules/timesheets/models/shift.models";

export const isShiftOverlap = (shifts: Shift[]): boolean => {
  if (shifts.length < 2) return false;

  const parsed_shifts = shifts.map(shift => ({
    start: date.extractDate(`${shift.date} ${shift.start_time}`, 'YYYY-MM-DD HH:mm').getTime(),
    end:   date.extractDate(`${shift.date} ${shift.end_time}`,   'YYYY-MM-DD HH:mm').getTime(),
  }));

  for (let i = 0; i < parsed_shifts.length; i++) {
    for (let j = i + 1; j < parsed_shifts.length; j++) {
      const parsed_shift_a = parsed_shifts[i];
      const parsed_shift_b = parsed_shifts[j];

      if (parsed_shift_a === undefined || parsed_shift_b === undefined) continue;

      if (Math.max(parsed_shift_a.start, parsed_shift_b.start) < Math.min(parsed_shift_a.end, parsed_shift_b.end)) {
        return true; // overlap found
      }
    }
  }

  return false;
};

export const useShiftRules = (time_required_error: string) =>  {
    const isTimeRequired: ValidationRule<string> = (time_string: string) => (!!time_string && patterns.testPattern.time(time_string)) || time_required_error;
    
    return {
        isTimeRequired,
    };
};
