import type { PastTreatment, PastTreatmentDetail } from '@/types/treatment';
import { isDetailEligibleForLabAttention } from '@/components/treatment/treatmentDetailRules';
import { isArchSentinel } from '@/components/treatment/prosthesisTree';

export type LabDispatchAttentionItem = {
  key: string;
  treatmentId: string;
  appointmentId: string;
  treatmentAt: string;
  detailClientId: string;
  detailNumber: number;
  detail: PastTreatmentDetail;
  isCurrentDraft: boolean;
};

function detailHasArchJobs(treatment: PastTreatment, detail: PastTreatmentDetail): boolean {
  const clientId = detail.clientId ?? detail.id;
  return treatment.labCases.some((lc) => {
    const linked =
      lc.detail?.clientId === clientId ||
      lc.detail?.id === detail.id ||
      lc.treatmentDetailId === detail.id;
    if (!linked) return false;
    return (lc.toothProsthesis ?? []).some(
      (tp) => isArchSentinel(tp.tooth) && Boolean(tp.prosthesisTypeCode),
    );
  });
}

function pushPendingDetails(
  items: LabDispatchAttentionItem[],
  treatment: PastTreatment,
  labDependentCodes: Set<string>,
  isCurrentDraft: boolean,
) {
  if (!treatment.appointmentId) {
    return;
  }

  treatment.details.forEach((detail, index) => {
    if (
      !isDetailEligibleForLabAttention(
        detail,
        labDependentCodes,
        isCurrentDraft,
        detailHasArchJobs(treatment, detail),
      )
    ) {
      return;
    }
    items.push({
      key: `${treatment.id}-${detail.clientId ?? detail.id}`,
      treatmentId: treatment.id,
      appointmentId: treatment.appointmentId!,
      treatmentAt: treatment.treatmentAt,
      detailClientId: detail.clientId ?? detail.id,
      detailNumber: index + 1,
      detail,
      isCurrentDraft,
    });
  });
}

/** Lab-dependent details that still need a lab send (current draft + saved history). */
export function collectLabDispatchAttention(
  labDependentCodes: Set<string>,
  currentDraft: PastTreatment | null,
  history: PastTreatment[],
  currentAppointmentId: string | null,
): LabDispatchAttentionItem[] {
  const items: LabDispatchAttentionItem[] = [];

  if (currentDraft) {
    pushPendingDetails(items, currentDraft, labDependentCodes, true);
  }

  for (const treatment of history) {
    if (currentAppointmentId && treatment.appointmentId === currentAppointmentId) {
      continue;
    }
    pushPendingDetails(items, treatment, labDependentCodes, false);
  }

  return items.sort(
    (a, b) => new Date(b.treatmentAt).getTime() - new Date(a.treatmentAt).getTime(),
  );
}
