import { describe, expect, it } from 'vitest';
import {
  canManagePolicies,
  filterPolicies,
  getPolicyCategoryFilters,
  isPolicyFormValid,
  toPolicyCategory,
  toPolicyCategoryFilter,
} from '@/business/policies/selectors';
import type { PolicyFormInput, PolicyViewModel } from '@/business/policies/types';
import { POLICY_CATEGORY_FILTERS } from '@/shared/constants/policies';

const policies: readonly PolicyViewModel[] = [
  {
    id: 'policy-1',
    title: 'Emergency Communication',
    category: 'Communication',
    content: 'Call families after a campus-wide emergency.',
    lastUpdated: '2026-06-08',
    updatedBy: 'Director',
  },
  {
    id: 'policy-2',
    title: 'Safety Drill',
    category: 'Safety',
    content: 'Monthly drill expectations.',
    lastUpdated: '2026-06-07',
    updatedBy: 'Office',
  },
  {
    id: 'policy-3',
    title: 'Behavior Support',
    category: 'Behavior',
    content: 'Use approved de-escalation supports.',
    lastUpdated: '2026-06-06',
    updatedBy: 'Director',
  },
];

describe('policy selectors', () => {
  it('allows the management tier (owner/superintendent/director/office_manager) to manage policies', () => {
    expect(canManagePolicies('owner')).toBe(true);
    expect(canManagePolicies('superintendent')).toBe(true);
    expect(canManagePolicies('director')).toBe(true);
    expect(canManagePolicies('office_manager')).toBe(true);
    expect(canManagePolicies('teacher')).toBe(false);
    expect(canManagePolicies('support_staff')).toBe(false);
    expect(canManagePolicies('student')).toBe(false);
  });

  it('returns the configured category filters without creating a new source of truth', () => {
    expect(getPolicyCategoryFilters()).toBe(POLICY_CATEGORY_FILTERS);
  });

  it('normalizes invalid categories and the all filter', () => {
    expect(toPolicyCategory('Safety')).toBe('Safety');
    expect(toPolicyCategory('Invalid')).toBe('Operations');
    expect(toPolicyCategoryFilter('all')).toBe('all');
    expect(toPolicyCategoryFilter('Legal')).toBe('Legal');
    expect(toPolicyCategoryFilter('Invalid')).toBe('Operations');
  });

  it('filters policies by trimmed search query and category', () => {
    expect(filterPolicies(policies, '  emergency ', 'all')).toEqual([policies[0]]);
    expect(filterPolicies(policies, 'drill', 'Safety')).toEqual([policies[1]]);
    expect(filterPolicies(policies, 'support', 'Safety')).toEqual([]);
  });

  it('validates required policy form fields', () => {
    const validInput: PolicyFormInput = {
      title: 'Safety',
      category: 'Safety',
      content: 'Required content.',
    };

    expect(isPolicyFormValid(validInput)).toBe(true);
    expect(isPolicyFormValid({ ...validInput, title: '   ' })).toBe(false);
    expect(isPolicyFormValid({ ...validInput, content: '' })).toBe(false);
  });
});
