import moment from "moment";

/** A `HH:mm[:ss]` value as a moment, or null when it is missing or unparseable. */
export function clockTime(value?: string | null) {
  if (!value) return null;
  const parsed = moment(value, ["HH:mm:ss", "HH:mm"], true);
  return parsed.isValid() ? parsed : null;
}

/**
 * Total contact time across the whole run: one day's hours times the number of
 * days, inclusive of both ends.
 *
 * Pure, and separate from the page, because the inclusive `+ 1` and the
 * minute rounding are the kind of arithmetic that is easy to "simplify" wrongly
 * — a three-day opportunity is three days, not two.
 *
 * Null when the record carries no daily time (the API sends `start_time:
 * null`): there is nothing to multiply, and «0:00» would read as a real figure.
 */
export function learnServeTotalDuration(
  opportunityData:
    | {
        start_date?: string;
        end_date?: string;
        start_time?: string | null;
        end_time?: string | null;
      }
    | undefined
): { hrs: number; mins: number } | null {
  if (!opportunityData) return null;
  const start = clockTime(opportunityData.start_time);
  const end = clockTime(opportunityData.end_time);
  if (!start || !end) return null;
  const hoursPerDay = moment.duration(end.diff(start)).asHours();
  const numberOfDays =
    moment(opportunityData.end_date).diff(
      moment(opportunityData.start_date),
      "days"
    ) + 1;
  const totalHours = hoursPerDay * numberOfDays;
  const hrs = Math.floor(totalHours);
  return { hrs, mins: Math.round((totalHours - hrs) * 60) };
}
