import { useDataSource } from "@erp/core/hooks";
import { ValidationErrorCollection } from "@repo/rdx-ddd";
import { DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
import { UpdateCustomerByIdRequestSchema } from "../../common";
import { Customer, CustomerFormData } from "../schemas";
import { toValidationErrors } from "./use-create-customer-mutation";
import {
  invalidateCustomerListCache,
  upsertCustomerIntoListCaches,
} from "./use-customer-list-query";
import { setCustomerDetailCache } from "./use-customer-query";

export const CUSTOMER_UPDATE_KEY = ["customers", "update"] as const;

type UpdateCustomerContext = {};

type UpdateCustomerPayload = {
  id: string;
  data: Partial<CustomerFormData>;
};

export function useUpdateCustomer() {
  const queryClient = useQueryClient();
  const dataSource = useDataSource();
  const schema = UpdateCustomerByIdRequestSchema;

  return useMutation<Customer, DefaultError, UpdateCustomerPayload, UpdateCustomerContext>({
    mutationKey: CUSTOMER_UPDATE_KEY,

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

      const result = schema.safeParse(data);
      if (!result.success) {
        throw new ValidationErrorCollection("Validation failed", toValidationErrors(result.error));
      }

      const updated = await dataSource.updateOne("customers", customerId, data);
      return updated as Customer;
    },

    onSuccess: (updated: Customer, variables) => {
      const { id: customerId } = updated;

      // Invalida el listado para refrescar desde servidor
      invalidateCustomerListCache(queryClient);

      // Actualiza detalle
      setCustomerDetailCache(queryClient, customerId, updated);

      // Actualiza todas las páginas donde aparezca
      upsertCustomerIntoListCaches(queryClient, { ...updated });
    },

    onSettled: () => {
      // Refresca todos los listados
      invalidateCustomerListCache(queryClient);
    },
  });
}
