import type { UserRole } from '@/shared/types/app';
import { POLICY_CATEGORIES, POLICY_CATEGORY_FILTERS, POLICY_DEFAULT_CATEGORY } from '@/shared/constants/policies';
import type { PolicyCategory, PolicyFormInput, PolicyViewModel } from '@/business/policies/types';

/**
 * Roles that may author policy/handbook documents — mirrors the backend grant of
 * `CREATE/UPDATE/DELETE_POLICY_DOCUMENTS` (owner/superintendent/director via full
 * access; office_manager via explicit grant). The backend stays the source of
 * truth; this only gates the management UI affordances.
 */
export function canManagePolicies(userRole: UserRole): boolean {
  return (
    userRole === 'owner' ||
    userRole === 'superintendent' ||
    userRole === 'director' ||
    userRole === 'office_manager'
  );
}

export function getPolicyCategoryFilters(): readonly (PolicyCategory | 'all')[] {
  return POLICY_CATEGORY_FILTERS;
}

export function toPolicyCategory(value: string): PolicyCategory {
  return POLICY_CATEGORIES.find((category) => category === value) ?? POLICY_DEFAULT_CATEGORY;
}

export function toPolicyCategoryFilter(value: string): PolicyCategory | 'all' {
  return value === 'all' ? 'all' : toPolicyCategory(value);
}

export function filterPolicies(
  policies: readonly PolicyViewModel[],
  searchQuery: string,
  categoryFilter: PolicyCategory | 'all',
): readonly PolicyViewModel[] {
  const normalizedSearchQuery = searchQuery.trim().toLowerCase();

  return policies.filter((policy) => {
    const matchesSearch = !normalizedSearchQuery
      || policy.title.toLowerCase().includes(normalizedSearchQuery)
      || policy.content.toLowerCase().includes(normalizedSearchQuery);
    const matchesCategory = categoryFilter === 'all' || policy.category === categoryFilter;

    return matchesSearch && matchesCategory;
  });
}

export function isPolicyFormValid(input: PolicyFormInput): boolean {
  return Boolean(input.title.trim() && input.content.trim());
}
