import type { LabCaseActivityItem } from '@/types/lab-case-activity';
import { APP_DATE, formatAppDateTime } from '@/lib/i18n/format';

type ActivityLabelTranslator = (
  key: string,
  values?: Record<string, string | number>,
) => string;

export function formatLabCaseActivityLine(
  activity: LabCaseActivityItem,
  t: ActivityLabelTranslator,
  locale: string,
): string {
  const actor = activity.actorName ?? t('activityUnknownActor');
  const date = formatAppDateTime(activity.createdAt, locale, APP_DATE.activity);

  switch (activity.type) {
    case 'CASE_SENT':
      return t('activityCaseSent', { date });
    case 'CLINIC_COMMENT':
      return t('activityClinicComment', {
        actor,
        preview: truncatePreview(activity.commentBody),
        date,
      });
    case 'LAB_COMMENT':
      return t('activityLabComment', {
        actor,
        preview: truncatePreview(activity.commentBody),
        date,
      });
    case 'TASK_COMPLETED':
      return t('activityTaskCompleted', {
        step: activity.stepLabel ?? t('activityUnknownStep'),
        actor,
        date,
      });
    case 'TASK_ASSIGNED':
      return t('activityTaskAssigned', {
        step: activity.stepLabel ?? t('activityUnknownStep'),
        actor,
        date,
      });
    case 'CASE_IMPORTANT':
      return t('activityCaseImportant', { actor, date });
    case 'CASE_AMENDED':
      return t('activityCaseAmended', { actor, date });
    default:
      return t('activityGeneric', { date });
  }
}

function truncatePreview(text: string | null | undefined, max = 60): string {
  const trimmed = text?.trim() ?? '';
  if (!trimmed) return '…';
  if (trimmed.length <= max) return trimmed;
  return `${trimmed.slice(0, max - 1)}…`;
}
