import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import {
  dispatchedRecords,
  OutgoingRecordQueryParams,
} from "@/record-management/services/api/recordOfficerService";
import { lockRecord } from "@/record-management/services/api/userRecordService";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

export const useOutgoingRecords = (params?: OutgoingRecordQueryParams) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const {
    data: recordsResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["outgoingRecords", params],
    queryFn: async () => {
      const data = await dispatchedRecords(params);

      return {
        count: data?.count,
        items: data?.items as RecordDto[],
      };
    },
    staleTime: 1 * 60 * 1000,
    retry: false,
  });
  const { mutate: makeRecordLocked, isPending: isLocking } = useMutation({
    mutationFn: ({
      recordId,
      isLocked,
    }: {
      recordId: string;
      isLocked: boolean;
    }) => lockRecord(recordId, isLocked),

    onSuccess: (_, variables) => {
      toast.success(
        variables.isLocked
          ? t("userIncoming.RecordLocked", "Record locked successfully")
          : t("userIncoming.RecordUnlocked", "Record unlocked successfully"),
      );

      // refresh relevant caches
      queryClient.invalidateQueries({ queryKey: ["outgoingRecords"] });
    },

    onError: (err: any) => {
      console.error("Failed to lock record", err);
      toast.error(
        t("userIncoming.LockUpdateFailed", "Failed to update record lock"),
      );
    },
  });

  return {
    recordsResponse,
    isLoading,
    isError,
    refetch,
    makeRecordLocked,
    isLocking,
  };
};
