import { useQuery } from '@tanstack/react-query';
import {
  createPolicyDocument,
  deletePolicyDocument,
  listPolicyDocuments,
  updatePolicyDocument,
} from '@/shared/api/policyDocuments';
import {
  acknowledgePolicyDocument,
  listMyPolicyAcknowledgments,
} from '@/shared/api/policyAcknowledgments';
import {
  POLICY_DOCUMENT_PAGE_CATEGORY,
  POLICY_QUERY_KEYS,
} from '@/shared/constants/policies';
import { toPolicyDocumentMutationDto, toPolicyViewModel } from '@/business/policies/mappers';
import type { PolicyFormInput } from '@/business/policies/types';
import { getApiListRows, 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(POLICY_DOCUMENT_PAGE_CATEGORY.handbookPolicies),
        toPolicyViewModel,
      ),
  });
}

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

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

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

/** The current user's persisted policy acknowledgments (replaces local state). */
export function usePolicyAcknowledgments() {
  return useQuery({
    queryKey: POLICY_QUERY_KEYS.acknowledgments,
    queryFn: () => getApiListRows(listMyPolicyAcknowledgments()),
  });
}

export function useAcknowledgePolicy() {
  return useInvalidatingMutation({
    mutationFn: (policyDocumentId: string) =>
      acknowledgePolicyDocument({ policyDocumentId }),
    invalidateQueryKey: POLICY_QUERY_KEYS.acknowledgments,
  });
}
