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

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());
}

export function isPolicyDocumentAcknowledged(
  acknowledgments: readonly PolicyAcknowledgmentDto[],
  policyDocumentId: string,
  version: number,
): boolean {
  return acknowledgments.some(
    (acknowledgment) =>
      acknowledgment.policyDocumentId === policyDocumentId
      && acknowledgment.version === version,
  );
}
