import { FrameEntryDto, FrameEntryMutationDto } from '@/shared/types/frame';
import { EditableFrameEntry, FrameEntryViewModel } from '@/business/frame/types';
import { formatWeekOf } from '@/shared/business/week';

function formatDisplayDate(isoDate: string): string {
  const date = new Date(isoDate);

  if (Number.isNaN(date.getTime())) {
    return isoDate;
  }

  return date.toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  });
}

export function toFrameEntryViewModel(dto: FrameEntryDto): FrameEntryViewModel {
  return {
    id: dto.id,
    weekStart: dto.week_of,
    weekLabel: dto.week_label ?? '',
    weekOf: formatWeekOf(dto.week_of),
    postedDate: formatDisplayDate(dto.posted_date),
    formal: dto.formal,
    recognition: dto.recognition,
    application: dto.application,
    management: dto.management,
    emotional: dto.emotional,
    author: dto.author,
  };
}

export function toFrameEntryMutationDto(entry: EditableFrameEntry): FrameEntryMutationDto {
  const weekLabel = entry.weekLabel.trim();
  return {
    week_of: entry.weekStart,
    week_label: weekLabel ? weekLabel : undefined,
    posted_date: entry.postedDate,
    formal: entry.formal,
    recognition: entry.recognition,
    application: entry.application,
    management: entry.management,
    emotional: entry.emotional,
    author: entry.author,
  };
}
