import { useDataSource } from "@erp/core/hooks";
import { DefaultError, QueryKey, useMutation, useQueryClient } from "@tanstack/react-query";
import { CustomersPage } from "../schemas";
import { cancelCustomerListQueries, deleteCustomerIntoListCaches } from "./use-customer-list-query";
import { invalidateCustomerDetailCache } from "./use-customer-query";

export const CUSTOMER_DELETE_KEY = ["customers", "delete"] as const;

type DeleteCustomerPayload = {
  id: string;
};

export function useDeleteCustomer() {
  const queryClient = useQueryClient();
  const dataSource = useDataSource();

  return useMutation<{ id: string }, DefaultError, DeleteCustomerPayload>({
    mutationKey: CUSTOMER_DELETE_KEY,

    mutationFn: async ({ id: customerId }) => {
      if (!customerId) {
        throw new Error("customerId is required");
      }

      await dataSource.deleteOne("customers", customerId);
      return { id: customerId };
    },

    onMutate: async ({ id }) => {
      await cancelCustomerListQueries(queryClient);
      return deleteCustomerIntoListCaches(queryClient, id);
    },

    onError: (_e, _v, ctx) => {
      if (!ctx) return;
      const { snapshots } = ctx as ReturnType<typeof deleteCustomerIntoListCaches>;
      for (const snap of snapshots as Array<{ key: QueryKey; page?: CustomersPage }>) {
        if (snap.page) queryClient.setQueryData(snap.key, snap.page);
      }
    },

    onSuccess: ({ id }) => {
      invalidateCustomerDetailCache(queryClient, id);
    },

    onSettled: (data) => {
      deleteCustomerIntoListCaches(queryClient, data?.id ?? "unknown");
    },
  });
}
