import {
  POLICY_DATE_NOT_RECORDED_LABEL,
  POLICY_DOCUMENT_PAGE_CATEGORY,
  POLICY_UPDATED_BY_LABEL,
} from '@/shared/constants/policies';
import type {
  PolicyDocumentMutationDto,
  PolicyDocumentDto,
} from '@/shared/types/policyDocuments';
import type {
  SafetyProtocolFormInput,
  SafetyProtocolViewModel,
} from '@/business/safety-protocols/types';

function toDateOnly(value: string | null): string {
  if (!value) {
    return POLICY_DATE_NOT_RECORDED_LABEL;
  }
  return value.split('T')[0] || POLICY_DATE_NOT_RECORDED_LABEL;
}

export function toSafetyProtocolViewModel(
  dto: PolicyDocumentDto,
): SafetyProtocolViewModel {
  return {
    id: dto.id,
    title: dto.title || '',
    tag: dto.tag,
    steps: dto.steps ?? [],
    autismConsiderations: dto.autism_considerations ?? [],
    version: dto.version,
    lastUpdated: toDateOnly(dto.updatedAt),
    author: dto.author || POLICY_UPDATED_BY_LABEL,
  };
}

export function toSafetyProtocolMutationDto(
  input: SafetyProtocolFormInput,
): PolicyDocumentMutationDto {
  return {
    title: input.title.trim(),
    category: POLICY_DOCUMENT_PAGE_CATEGORY.safetyProtocols,
    tag: input.tag,
    steps: input.steps.map((step) => step.trim()).filter(Boolean),
    autism_considerations: input.autismConsiderations
      .map((item) => item.trim())
      .filter(Boolean),
  };
}
