import { differenceInMinutes } from 'date-fns';
import { roundHours } from './helpers';

type Break = {
  break_start: Date;
  break_end: Date;
};

const getMinutes = (start: Date, end: Date): number => {
  if (!start || !end) return 0;
  const minutes = differenceInMinutes(end, start);
  return Math.max(minutes, 0);
};

export const calculateBreakHours = (
  lunchBreak: Break | null,
  timeBreaks: Break[],
): number => {
  let totalMinutes = 0;

  if (lunchBreak) {
    totalMinutes += getMinutes(lunchBreak.break_start, lunchBreak.break_end);
  }
  for (let i = 0; i < timeBreaks.length; i++) {
    const b = timeBreaks[i];
    totalMinutes += getMinutes(b.break_start, b.break_end);
  }
  const hours = totalMinutes / 60;
  return Math.max(roundHours(hours), 0);
};

export const calculateDuration = (start: Date, end: Date): number => {
  const minutes = differenceInMinutes(end, start);
  const hours = minutes / 60;
  return Math.max(roundHours(hours), 0);
};
