"use server";

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { readCart, writeCart, clearCart as clearCartCookie } from "@/lib/store/cart";

const addSchema = z.object({
  productId: z.string().uuid(),
  quantity: z.coerce.number().int().min(1).max(10).default(1),
});

/**
 * Add a product to the cookie cart. Called via form submit from the
 * product detail page's "Add to cart" button. Safe to call when the cart is
 * empty or when the product is already there (increments qty).
 */
export async function addToCart(formData: FormData) {
  const parsed = addSchema.parse({
    productId: formData.get("productId"),
    quantity: formData.get("quantity") ?? 1,
  });
  const current = await readCart();
  const existing = current.find((l) => l.productId === parsed.productId);
  const next = existing
    ? current.map((l) =>
        l.productId === parsed.productId
          ? { ...l, quantity: Math.min(100, l.quantity + parsed.quantity) }
          : l,
      )
    : [...current, { productId: parsed.productId, quantity: parsed.quantity }];
  await writeCart(next);
  revalidatePath("/products/store/cart");
}

const updateSchema = z.object({
  productId: z.string().uuid(),
  quantity: z.coerce.number().int().min(0).max(100),
});

export async function updateCartLine(formData: FormData) {
  const parsed = updateSchema.parse({
    productId: formData.get("productId"),
    quantity: formData.get("quantity"),
  });
  const current = await readCart();
  const next =
    parsed.quantity === 0
      ? current.filter((l) => l.productId !== parsed.productId)
      : current.map((l) =>
          l.productId === parsed.productId
            ? { ...l, quantity: parsed.quantity }
            : l,
        );
  await writeCart(next);
  revalidatePath("/products/store/cart");
}

export async function removeCartLine(formData: FormData) {
  const productId = z.string().uuid().parse(formData.get("productId"));
  const current = await readCart();
  await writeCart(current.filter((l) => l.productId !== productId));
  revalidatePath("/products/store/cart");
}

export async function clearCart() {
  await clearCartCookie();
  revalidatePath("/products/store/cart");
}
