"use server";

import { cookies } from "next/headers";
import { redirect, unstable_rethrow } from "next/navigation";
import { checkoutSchema } from "@/lib/validation";
import { getCartToken, clearCartCookie } from "@/lib/cart";
import { placeOrder, OrderError } from "@/lib/orders";
import { getSessionUser } from "@/lib/auth-helpers";
import { sendOrderConfirmation } from "@/lib/email";
import { rateLimit } from "@/lib/rate-limit";
import type { Locale } from "@/lib/i18n/config";
import { actionMessage, type ActionMessageKey } from "@/lib/action-messages";

export type CheckoutState = {
  status: "idle" | "error" | "success";
  message?: string;
  fieldErrors?: Record<string, string[]>;
};

export async function placeOrderAction(
  _prev: CheckoutState,
  formData: FormData,
): Promise<CheckoutState> {
  const locale = ((formData.get("locale") as string) || "fr") as Locale;
  const parsed = checkoutSchema.safeParse({
    fullName: formData.get("fullName"),
    email: formData.get("email"),
    phone: formData.get("phone"),
    country: formData.get("country"),
    city: formData.get("city"),
    addressLine1: formData.get("addressLine1"),
    addressLine2: formData.get("addressLine2") || "",
    postalCode: formData.get("postalCode") || "",
    notes: formData.get("notes") || "",
    paymentMethod: formData.get("paymentMethod"),
    locale: (formData.get("locale") as string) || "fr",
  });

  if (!parsed.success) {
    return {
      status: "error",
      message: actionMessage(locale, "verifyCheckout"),
      fieldErrors: parsed.error.flatten().fieldErrors,
    };
  }

  const limit = rateLimit(`checkout:${parsed.data.email}`, 5, 10 * 60 * 1000);
  if (!limit.success) {
    return { status: "error", message: actionMessage(locale, "tooManyAttempts") };
  }

  const token = await getCartToken();
  if (!token) return { status: "error", message: actionMessage(locale, "cartEmpty") };

  const user = await getSessionUser();

  try {
    const order = await placeOrder({
      cartToken: token,
      userId: user?.id ?? null,
      locale,
      paymentMethod: parsed.data.paymentMethod,
      customerName: parsed.data.fullName,
      email: parsed.data.email,
      phone: parsed.data.phone,
      country: parsed.data.country,
      city: parsed.data.city,
      addressLine1: parsed.data.addressLine1,
      addressLine2: parsed.data.addressLine2 || undefined,
      postalCode: parsed.data.postalCode || undefined,
      notes: parsed.data.notes || undefined,
    });

    const store = await cookies();
    store.set("dz_last_order", order.reference, {
      httpOnly: true,
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production",
      path: "/",
      maxAge: 60 * 60 * 24,
    });

    await clearCartCookie();
    await sendOrderConfirmation(order, locale).catch(() => false);

    redirect(`/${locale}/checkout/success/${order.reference}`);
  } catch (error) {
    unstable_rethrow(error);
    if (error instanceof OrderError) {
      const key: ActionMessageKey =
        error.code === "EMPTY_CART"
          ? "cartEmpty"
          : error.code === "COUPON_INVALID"
            ? "couponMaxUses"
            : error.code === "OUT_OF_STOCK"
              ? "stockUnavailable"
              : "orderFailed";
      return { status: "error", message: actionMessage(locale, key) };
    }
    console.error("[checkout] order failed", error);
    return {
      status: "error",
      message: actionMessage(locale, "orderFailed"),
    };
  }
}