import { useState } from "react";
import { placeOrder, OrderPayload } from "@/services/orderApi";
import { getCartIdentifier } from "@/utils";

export function useOrder() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [orderId, setOrderId] = useState<string | null>(null);

  const submitOrder = async (payload: Omit<OrderPayload, "customer_id" | "guest_id">) => {
    setLoading(true);
    setError(null);

    // automatically attach user or guest identifier
    const identifier = getCartIdentifier();

    // map to order's expected field names
    const orderIdentifier = "user" in identifier && identifier.user
    ? { customer_id: identifier.user }
    : { guest_id: (identifier as any).guestId };

    const fullPayload = { ...orderIdentifier, ...payload } as OrderPayload;

    const { data, error } = await placeOrder(fullPayload);

    if (error) {
      setError(error);
    } else {
      setOrderId(data?.orderId ?? data?._id ?? null);
    }

    setLoading(false);
    return { data, error };
  };

  return { submitOrder, loading, error, orderId };
}