import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";

import {
  signaturesService,
  type SaveSignaturePayload,
} from "@/services/signatures.service";

const SAVED_SIGNATURE_KEY = ["me", "signature"] as const;

export function useMySignature() {
  return useQuery({
    queryKey: SAVED_SIGNATURE_KEY,
    queryFn: () => signaturesService.getMySignature(),
    staleTime: 60_000,
  });
}

export function useSaveSignature() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: SaveSignaturePayload) =>
      signaturesService.saveMySignature(payload),
    onSuccess: () => {
      toast.success("Signature saved");
      void qc.invalidateQueries({ queryKey: SAVED_SIGNATURE_KEY });
    },
    onError: () => toast.error("Failed to save signature"),
  });
}
