import { useQuery } from '@tanstack/react-query';
import {
  createDocument,
  deleteDocument,
  listPolicyDocuments,
  updateDocument,
} from '@/shared/api/documents';
import { POLICY_QUERY_KEYS } from '@/shared/constants/policies';
import { toPolicyDocumentMutationDto, toPolicyViewModel } from '@/business/policies/mappers';
import type { PolicyFormInput } from '@/business/policies/types';
import { mapApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';

interface PolicyUpdateInput {
  readonly id: string;
  readonly policy: PolicyFormInput;
}

export function usePolicies() {
  return useQuery({
    queryKey: POLICY_QUERY_KEYS.documents,
    queryFn: () => mapApiListRows(listPolicyDocuments(), toPolicyViewModel),
  });
}

export function useCreatePolicy() {
  return useInvalidatingMutation({
    mutationFn: (input: PolicyFormInput) => createDocument(toPolicyDocumentMutationDto(input)),
    invalidateQueryKey: POLICY_QUERY_KEYS.documents,
  });
}

export function useUpdatePolicy() {
  return useInvalidatingMutation({
    mutationFn: (input: PolicyUpdateInput) => updateDocument(
      input.id,
      toPolicyDocumentMutationDto(input.policy),
    ),
    invalidateQueryKey: POLICY_QUERY_KEYS.documents,
  });
}

export function useDeletePolicy() {
  return useInvalidatingMutation({
    mutationFn: (id: string) => deleteDocument(id),
    invalidateQueryKey: POLICY_QUERY_KEYS.documents,
  });
}
