import { serve } from "@upstash/workflow/nextjs"
import {
  createOrderId,
  checkStockAvailability,
  processPayment,
  dispatchOrder,
  sendOrderConfirmation,
  sendDispatchNotification,
} from "./utils"
type OrderPayload = {
  userId: string
  items: { productId: string, quantity: number }[]
}
export const { POST } = serve<OrderPayload>(async (context) => {
  const { userId, items } = context.requestPayload;
  // Step 1: Create Order Id
  const orderId = await context.run("create-order-id", async () => {
    return await createOrderId(userId);
  });
  // Step 2: Verify stock availability
  const stockAvailable = await context.run("check-stock", async () => {
    return await checkStockAvailability(items);
  });
  if (!stockAvailable) {
    console.warn("Some items are out of stock");
    return;
  };
  // Step 3: Process payment
  await context.run("process-payment", async () => {
    return await processPayment(orderId)
  })
  // Step 4: Dispatch the order
  await context.run("dispatch-order", async () => {
    return await dispatchOrder(orderId, items)
  })
  // Step 5: Send order confirmation email
  await context.run("send-confirmation", async () => {
    return await sendOrderConfirmation(userId, orderId)
  })
  // Step 6: Send dispatch notification
  await context.run("send-dispatch-notification", async () => {
    return await sendDispatchNotification(userId, orderId)
  })
})