import { startOfLocalDay } from '@/components/appointments/appointmentTime';
import type { PastTreatment } from '@/types/treatment';

export type TreatmentHistoryFilters = {
  notShippedOnly: boolean;
  date: string;
};

export function treatmentHasUnshippedProsthesis(
  treatment: PastTreatment,
  labDependentCodes: Set<string>,
): boolean {
  return treatment.details.some(
    (detail) => labDependentCodes.has(detail.treatmentType) && !detail.sentAt,
  );
}

export function treatmentMatchesHistoryDate(treatmentAt: string, date: string): boolean {
  if (!date) return true;

  const treatmentDay = startOfLocalDay(new Date(treatmentAt)).getTime();
  const filterDay = startOfLocalDay(new Date(`${date}T00:00:00`)).getTime();
  return treatmentDay === filterDay;
}

export function filterTreatmentHistoryItems(
  history: PastTreatment[],
  labDependentCodes: Set<string>,
  filters: TreatmentHistoryFilters,
  excludeAppointmentId?: string | null,
): PastTreatment[] {
  const source = excludeAppointmentId
    ? history.filter((item) => item.appointmentId !== excludeAppointmentId)
    : history;

  return source.filter((treatment) => {
    if (!treatmentMatchesHistoryDate(treatment.treatmentAt, filters.date)) {
      return false;
    }
    if (filters.notShippedOnly && !treatmentHasUnshippedProsthesis(treatment, labDependentCodes)) {
      return false;
    }
    return true;
  });
}
