"use server";

/** ثبت سفارش و دریافت آدرس درگاه */
import { z } from "zod";
import { getCurrentUser } from "@/server/auth/session";
import { CheckoutError, placeOrder } from "@/server/services/checkout";
import { discountCodeSchema } from "@/validation/common";
import { isPrelaunch, PRELAUNCH_MESSAGE } from "@/lib/prelaunch";

const input = z.object({
  addressId: z.string().min(1).max(40),
  shippingMethodId: z.string().min(1).max(30),
  discountCode: discountCodeSchema.optional(),
});

export async function placeOrderAction(raw: unknown): Promise<{ ok: true; redirectUrl: string } | { ok: false; error: string }> {
  if (isPrelaunch()) return { ok: false, error: PRELAUNCH_MESSAGE };
  const user = await getCurrentUser();
  if (!user) return { ok: false, error: "ابتدا وارد حساب شوید" };
  const parsed = input.safeParse(raw);
  if (!parsed.success) return { ok: false, error: "اطلاعات سفارش کامل نیست" };
  try {
    return { ok: true, ...(await placeOrder(user, parsed.data)) };
  } catch (err) {
    if (err instanceof CheckoutError) return { ok: false, error: err.message };
    console.error("[checkout]", err);
    return { ok: false, error: "خطایی رخ داد؛ دوباره تلاش کنید" };
  }
}
