import { afterEach, describe, expect, it, vi } from 'vitest';
import {
  toPolicyDocumentMutationDto,
  toPolicyViewModel,
} from '@/business/policies/mappers';
import type { PolicyFormInput } from '@/business/policies/types';
import {
  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 } from '@/shared/types/documents';

describe('policy mappers', () => {
  afterEach(() => {
    vi.useRealTimers();
  });

  it('maps backend document DTO fields into the frontend policy view model shape', () => {
    const dto: DocumentDto = {
      id: 'policy-1',
      entity_type: 'organization',
      entity_reference: 'Safety',
      name: 'Incident Response',
      category: 'policy',
      uploaded_at: '2026-06-07T08:00:00.000Z',
      notes: 'Use the approved incident response process.',
      organizationId: 'org-1',
      campusId: null,
      createdById: 'user-1',
      updatedById: 'user-2',
      createdAt: '2026-06-07T08:00:00.000Z',
      updatedAt: '2026-06-08T09:30:00.000Z',
    };

    expect(toPolicyViewModel(dto)).toEqual({
      id: 'policy-1',
      title: 'Incident Response',
      category: 'Safety',
      content: 'Use the approved incident response process.',
      lastUpdated: '2026-06-08',
      updatedBy: POLICY_UPDATED_BY_LABEL,
    });
  });

  it('defaults missing document fields into explicit policy view model values', () => {
    const dto: DocumentDto = {
      id: 'policy-2',
      entity_type: null,
      entity_reference: 'Unknown Category',
      name: null,
      category: null,
      uploaded_at: null,
      notes: null,
      organizationId: null,
      campusId: null,
      createdById: null,
      updatedById: null,
      createdAt: '2026-06-07T08:00:00.000Z',
      updatedAt: '',
    };

    expect(toPolicyViewModel(dto)).toEqual({
      id: 'policy-2',
      title: '',
      category: POLICY_DEFAULT_CATEGORY,
      content: '',
      lastUpdated: POLICY_DATE_NOT_RECORDED_LABEL,
      updatedBy: POLICY_UPDATED_BY_LABEL,
    });
  });

  it('maps policy form input back into the backend document mutation DTO shape', () => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-06-08T12:34:56.000Z'));

    const input: PolicyFormInput = {
      title: '  Communication Standards  ',
      category: 'Communication',
      content: '  Use plain language with families.  ',
    };

    expect(toPolicyDocumentMutationDto(input)).toEqual({
      entity_type: POLICY_DOCUMENT_ENTITY_TYPE,
      entity_reference: 'Communication',
      name: 'Communication Standards',
      category: POLICY_DOCUMENT_CATEGORY,
      uploaded_at: '2026-06-08T12:34:56.000Z',
      notes: 'Use plain language with families.',
    });
  });
});
