import { useDataSource } from "@erp/core/hooks";
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
import { DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
import { CreateCustomerInvoiceRequestSchema } from "../../common";
import { CustomerInvoice, InvoiceFormData } from "../schemas";

type CreateCustomerInvoicePayload = {
  data: InvoiceFormData;
};

export const useCreateCustomerInvoiceMutation = () => {
  const queryClient = useQueryClient();
  const dataSource = useDataSource();
  const schema = CreateCustomerInvoiceRequestSchema;

  return useMutation<CustomerInvoice, DefaultError, CreateCustomerInvoicePayload>({
    mutationKey: ["customer-invoice:create"],

    mutationFn: async (payload) => {
      const { data } = payload;
      const invoiceId = UniqueID.generateNewID();

      const newInvoiceData = {
        ...data,
        id: invoiceId.toString(),
      };

      const result = schema.safeParse(newInvoiceData);
      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 created = await dataSource.createOne("customer-invoices", newInvoiceData);
      return created as CustomerInvoice;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["customer-invoices"] });
    },
  });
};
