import { useDataSource } from "@erp/core/hooks";
import { ValidationErrorCollection } from "@repo/rdx-ddd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { UpdateCustomerByIdRequestDTO, UpdateCustomerByIdRequestSchema } from "../../common";
import { CustomerFormData } from "../schemas";
import { CUSTOMER_QUERY_KEY } from "./use-customer-query";

export const CUSTOMERS_LIST_KEY = ["customers"] 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<CustomerFormData, Error, UpdateCustomerPayload, UpdateCustomerContext>({
    mutationKey: ["customer:update"], //, customerId],

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

      const result = schema.safeParse(data);
      if (!result.success) {
        // Construye errores detallados
        const validationErrors = result.error.issues.map((err) => ({
          field: err.path.join("."),
          message: err.message,
        }));

        throw new ValidationErrorCollection("Validation failed", validationErrors);
      }

      const updated = await dataSource.updateOne("customers", customerId, data);
      return updated as CustomerFormData;
    },
    onSuccess: (updated: CustomerFormData, variables) => {
      const { id: customerId } = variables;

      // Refresca inmediatamente el detalle
      queryClient.setQueryData<UpdateCustomerByIdRequestDTO>(
        CUSTOMER_QUERY_KEY(customerId),
        updated
      );

      // Otra opción es invalidar el detalle para forzar refetch:
      // queryClient.invalidateQueries({ queryKey: CUSTOMER_QUERY_KEY(customerId) });

      // Invalida el listado para refrescar desde servidor
      queryClient.invalidateQueries({ queryKey: CUSTOMERS_LIST_KEY });
    },
  });
}
