"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/prisma";
import { ensureCart, getCartToken, getCartView } from "@/lib/cart";
import { getSessionUser } from "@/lib/auth-helpers";
import { cartItemSchema, couponCodeSchema, updateCartItemSchema } from "@/lib/validation";
import { evaluateCoupon } from "@/lib/coupons";
import { actionMessage } from "@/lib/action-messages";

export type CartActionState = {
  status: "idle" | "success" | "error";
  message?: string;
  count?: number;
};

function refresh(locale: string) {
  revalidatePath(`/${locale}`, "layout");
  revalidatePath(`/${locale}/cart`);
}

export async function addToCartAction(
  _prev: CartActionState,
  formData: FormData,
): Promise<CartActionState> {
  const parsed = cartItemSchema.safeParse({
    productId: formData.get("productId"),
    variantId: (formData.get("variantId") as string) || null,
    quantity: Number(formData.get("quantity") ?? 1),
    locale: (formData.get("locale") as string) || "fr",
  });

  if (!parsed.success) {
    return { status: "error", message: actionMessage("fr", "invalidSelection") };
  }

  const { productId, variantId, quantity, locale } = parsed.data;

  const product = await prisma.product.findUnique({
    where: { id: productId },
    include: { variants: true },
  });

  if (!product || !product.isPublished) {
    return { status: "error", message: actionMessage(locale, "unavailable") };
  }

  if (product.variants.length > 0 && !variantId) {
    return { status: "error", message: actionMessage(locale, "chooseOption") };
  }

  const variant = variantId ? product.variants.find((item) => item.id === variantId) : null;
  if (variantId && !variant) {
    return { status: "error", message: actionMessage(locale, "optionGone") };
  }

  const stock = variant ? Math.min(variant.stock, product.stock) : product.stock;
  if (stock < 1) {
    return { status: "error", message: actionMessage(locale, "soldOut") };
  }

  const user = await getSessionUser();
  const cart = await ensureCart(user?.id);

  const existing = await prisma.cartItem.findFirst({
    where: { cartId: cart.id, productId, variantId: variantId ?? null },
  });

  const nextQuantity = Math.min((existing?.quantity ?? 0) + quantity, stock, 20);

  if (existing) {
    await prisma.cartItem.update({ where: { id: existing.id }, data: { quantity: nextQuantity } });
  } else {
    await prisma.cartItem.create({
      data: { cartId: cart.id, productId, variantId: variantId ?? null, quantity: nextQuantity },
    });
  }

  const view = await getCartView(locale as "fr" | "en" | "ar");
  refresh(locale);

  return {
    status: "success",
    message: stock < quantity + (existing?.quantity ?? 0) ? actionMessage(locale, "stockAdjusted") : actionMessage(locale, "added"),
    count: view?.items.reduce((sum, item) => sum + item.quantity, 0) ?? quantity,
  };
}

export async function updateCartItemAction(input: {
  itemId: string;
  quantity: number;
  locale: string;
}): Promise<{ ok: boolean; message?: string }> {
  const parsed = updateCartItemSchema.safeParse(input);
  if (!parsed.success) return { ok: false, message: actionMessage(input.locale, "invalidQuantity") };

  const token = await getCartToken();
  if (!token) return { ok: false, message: actionMessage(parsed.data.locale, "cartNotFound") };

  const item = await prisma.cartItem.findFirst({
    where: { id: parsed.data.itemId, cart: { token } },
    include: { product: true, variant: true },
  });
  if (!item) return { ok: false, message: actionMessage(parsed.data.locale, "itemNotFound") };

  if (parsed.data.quantity === 0) {
    await prisma.cartItem.delete({ where: { id: item.id } });
    refresh(parsed.data.locale);
    return { ok: true };
  }

  const stock = item.variant ? Math.min(item.variant.stock, item.product.stock) : item.product.stock;
  if (parsed.data.quantity > stock) {
    return { ok: false, message: actionMessage(parsed.data.locale, "stockLeft", { count: stock }) };
  }

  await prisma.cartItem.update({
    where: { id: item.id },
    data: { quantity: Math.min(parsed.data.quantity, 20) },
  });
  refresh(parsed.data.locale);
  return { ok: true };
}

export async function removeCartItemAction(input: {
  itemId: string;
  locale: string;
}): Promise<{ ok: boolean }> {
  const token = await getCartToken();
  if (!token) return { ok: false };
  const item = await prisma.cartItem.findFirst({ where: { id: input.itemId, cart: { token } } });
  if (!item) return { ok: false };
  await prisma.cartItem.delete({ where: { id: item.id } });
  refresh(input.locale);
  return { ok: true };
}

export async function applyCouponAction(
  _prev: CartActionState,
  formData: FormData,
): Promise<CartActionState> {
  const locale = (formData.get("locale") as string) || "fr";
  const raw = couponCodeSchema.safeParse(formData.get("code"));
  if (!raw.success) return { status: "error", message: actionMessage(locale, "invalidCoupon") };

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

  const cart = await prisma.cart.findUnique({
    where: { token },
    include: { items: { include: { product: true, variant: true } } },
  });
  if (!cart || cart.items.length === 0) {
    return { status: "error", message: actionMessage(locale, "cartEmpty") };
  }

  const subtotal = cart.items.reduce(
    (sum, item) => sum + (item.product.price + (item.variant?.priceDelta ?? 0)) * item.quantity,
    0,
  );

  const coupon = await prisma.coupon.findUnique({ where: { code: raw.data } });
  const result = evaluateCoupon(coupon, subtotal);
  if (!result.ok) {
    const key = result.reason === "expired"
      ? "couponExpired"
      : result.reason === "not_started"
        ? "couponNotStarted"
        : result.reason === "min_order"
          ? "couponMinOrder"
          : result.reason === "max_uses"
            ? "couponMaxUses"
            : "invalidCoupon";
    return { status: "error", message: actionMessage(locale, key) };
  }

  await prisma.cart.update({ where: { id: cart.id }, data: { couponCode: raw.data } });
  refresh(locale);
  return { status: "success", message: actionMessage(locale, "couponApplied") };
}

export async function removeCouponAction(_prev: CartActionState, formData: FormData): Promise<CartActionState> {
  const locale = (formData.get("locale") as string) || "fr";
  const token = await getCartToken();
  if (token) {
    await prisma.cart.updateMany({ where: { token }, data: { couponCode: null } });
  }
  refresh(locale);
  return { status: "success", message: actionMessage(locale, "couponRemoved") };
}