import { useDataSource } from "@erp/core/hooks";
import { ValidationErrorCollection } from "@repo/rdx-ddd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  UpdateCustomerInvoiceByIdRequestDTO,
  UpdateCustomerInvoiceByIdRequestSchema,
} from "../../common";
import { InvoiceFormData } from "../schemas";
import { CUSTOMER_INVOICE_QUERY_KEY } from "./use-invoice-query";

export const CUSTOMER_INVOICES_LIST_KEY = ["customer-invoices"] as const;

type UpdateCustomerInvoiceContext = {};

type UpdateCustomerInvoicePayload = {
  id: string;
  data: Partial<InvoiceFormData>;
};

export function useUpdateCustomerInvoice() {
  const queryClient = useQueryClient();
  const dataSource = useDataSource();
  const schema = UpdateCustomerInvoiceByIdRequestSchema;

  return useMutation<
    InvoiceFormData,
    Error,
    UpdateCustomerInvoicePayload,
    UpdateCustomerInvoiceContext
  >({
    mutationKey: ["customer-invoice:update"], //, customerId],

    mutationFn: async (payload) => {
      const { id: invoiceId, data } = payload;

      console.log(payload);

      if (!invoiceId) {
        throw new Error("customerInvoiceId is required");
      }

      const result = schema.safeParse(data);
      if (!result.success) {
        console.log(result);

        // 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("customer-invoices", invoiceId, data);
      return updated as InvoiceFormData;
    },
    onSuccess: (updated: InvoiceFormData, variables) => {
      const { id: invoiceId } = variables;

      // Refresca inmediatamente el detalle
      queryClient.setQueryData<UpdateCustomerInvoiceByIdRequestDTO>(
        CUSTOMER_INVOICE_QUERY_KEY(invoiceId),
        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: CUSTOMER_INVOICES_LIST_KEY });
    },
  });
}
