import type { LinkedOrganizationOption, TreatmentCaseSendInfo } from '@/types/treatment';
import { formatAppDateTime } from '@/lib/i18n/format';

export type CaseSendLabelT = (
  key: 'sentToAt' | 'fallbackOrgName',
  values?: { orgName: string; datetime: string },
) => string;

export function formatCaseSentLines(
  sends: TreatmentCaseSendInfo[] | undefined,
  fallback: {
    organizationIds: string[];
    sentAt: string | null;
    orgs?: LinkedOrganizationOption[];
  } | undefined,
  t: CaseSendLabelT,
  locale: string,
): string[] {
  if (sends?.length) {
    return sends.map((s) => {
      const at = formatAppDateTime(s.sentAt, locale, { dateStyle: 'medium', timeStyle: 'short' });
      return t('sentToAt', { orgName: s.organizationName, datetime: at });
    });
  }

  if (fallback?.sentAt && fallback.organizationIds.length > 0) {
    const at = formatAppDateTime(fallback.sentAt, locale, { dateStyle: 'medium', timeStyle: 'short' });
    const nameById = new Map(fallback.orgs?.map((o) => [o.id, o.name]) ?? []);
    return fallback.organizationIds.map((id) => {
      const name = nameById.get(id) ?? t('fallbackOrgName');
      return t('sentToAt', { orgName: name, datetime: at });
    });
  }

  return [];
}

export function formatCaseSentSummary(
  sends: TreatmentCaseSendInfo[] | undefined,
  fallback: {
    organizationIds: string[];
    sentAt: string | null;
    orgs?: LinkedOrganizationOption[];
  } | undefined,
  t: CaseSendLabelT,
  locale: string,
): string | null {
  const lines = formatCaseSentLines(sends, fallback, t, locale);
  return lines.length > 0 ? lines.join(' · ') : null;
}
