import {
  POLICY_CATEGORIES,
  POLICY_DATE_NOT_RECORDED_LABEL,
  POLICY_DEFAULT_CATEGORY,
  POLICY_DOCUMENT_CATEGORY,
  POLICY_DOCUMENT_ENTITY_TYPE,
  POLICY_UPDATED_BY_LABEL,
} from '@/shared/constants/policies';
import type { DocumentDto, DocumentMutationDto } from '@/shared/types/documents';
import type { PolicyCategory, PolicyFormInput, PolicyViewModel } from '@/business/policies/types';

function isPolicyCategory(value: string | null): value is PolicyCategory {
  return POLICY_CATEGORIES.some((category) => category === value);
}

function toPolicyCategory(value: string | null): PolicyCategory {
  return isPolicyCategory(value) ? value : POLICY_DEFAULT_CATEGORY;
}

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 toPolicyViewModel(dto: DocumentDto): PolicyViewModel {
  return {
    id: dto.id,
    title: dto.name || '',
    category: toPolicyCategory(dto.entity_reference),
    content: dto.notes || '',
    lastUpdated: toDateOnly(dto.updatedAt || dto.uploaded_at),
    updatedBy: POLICY_UPDATED_BY_LABEL,
  };
}

export function toPolicyDocumentMutationDto(input: PolicyFormInput): DocumentMutationDto {
  const recordedAt = new Date().toISOString();

  return {
    entity_type: POLICY_DOCUMENT_ENTITY_TYPE,
    entity_reference: input.category,
    name: input.title.trim(),
    category: POLICY_DOCUMENT_CATEGORY,
    uploaded_at: recordedAt,
    notes: input.content.trim(),
  };
}
