import {
  POLICY_CATEGORIES,
  POLICY_DATE_NOT_RECORDED_LABEL,
  POLICY_DEFAULT_CATEGORY,
  POLICY_DOCUMENT_PAGE_CATEGORY,
  POLICY_UPDATED_BY_LABEL,
} from '@/shared/constants/policies';
import type {
  PolicyDocumentDto,
  PolicyDocumentMutationDto,
} from '@/shared/types/policyDocuments';
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;
}

/**
 * Maps a unified `policy_documents` row (category `handbook_policy`) into the
 * handbook page's view model. The handbook's sub-category lives in `tag`.
 */
export function toPolicyViewModel(dto: PolicyDocumentDto): PolicyViewModel {
  return {
    id: dto.id,
    title: dto.title || '',
    category: toPolicyCategory(dto.tag),
    content: dto.body || '',
    lastUpdated: toDateOnly(dto.updatedAt),
    updatedBy: dto.author || POLICY_UPDATED_BY_LABEL,
  };
}

export function toPolicyDocumentMutationDto(
  input: PolicyFormInput,
): PolicyDocumentMutationDto {
  return {
    title: input.title.trim(),
    category: POLICY_DOCUMENT_PAGE_CATEGORY.handbookPolicies,
    tag: input.category,
    body: input.content.trim(),
  };
}
