import { useDataSource } from "@erp/core/hooks";
import { UniqueID, ValidationErrorCollection } from "@repo/rdx-ddd";
import { DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
import { CreateCustomerRequestSchema } from "../../common";
import { Customer, CustomerFormData } from "../schemas";
import { CUSTOMERS_LIST_KEY } from "./use-update-customer-mutation";

type CreateCustomerPayload = {
  data: CustomerFormData;
};

export function useCreateCustomer() {
  const queryClient = useQueryClient();
  const dataSource = useDataSource();
  const schema = CreateCustomerRequestSchema;

  return useMutation<Customer, DefaultError, CreateCustomerPayload>({
    mutationKey: ["customer:create"],

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

      const newCustomerData = {
        ...data,
        id: customerId.toString(),
      };

      const result = schema.safeParse(newCustomerData);
      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("customers", newCustomerData);
      return created as Customer;
    },

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