"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { slugify } from "@/lib/slug";
import { requirePermission } from "@/lib/permissions";

export async function createCollection(formData: FormData) {
  await requirePermission("products", "add");
  const name = String(formData.get("name") ?? "").trim();
  if (!name) redirect("/iv-manage-84x2/collections?error=Name+is+required");

  const slug = slugify(name);
  const existing = await prisma.collection.findUnique({ where: { slug } });
  if (existing) redirect("/iv-manage-84x2/collections?error=A+collection+with+that+name+already+exists");

  await prisma.collection.create({ data: { name, slug } });
  revalidatePath("/iv-manage-84x2/collections");
  revalidatePath("/");
  redirect("/iv-manage-84x2/collections?success=Collection+added.");
}

export async function deleteCollection(id: string) {
  await requirePermission("products", "delete");
  await prisma.collection.delete({ where: { id } });
  revalidatePath("/iv-manage-84x2/collections");
  revalidatePath("/");
  redirect("/iv-manage-84x2/collections?success=Collection+deleted.");
}

export async function addProductToCollection(collectionId: string, productId: string) {
  await requirePermission("products", "edit");
  await prisma.collection.update({
    where: { id: collectionId },
    data: { products: { connect: { id: productId } } },
  });
  revalidatePath(`/iv-manage-84x2/collections/${collectionId}`);
  revalidatePath("/");
  redirect(`/iv-manage-84x2/collections/${collectionId}?success=Product+added+to+collection.`);
}

export async function removeProductFromCollection(collectionId: string, productId: string) {
  await requirePermission("products", "edit");
  await prisma.collection.update({
    where: { id: collectionId },
    data: { products: { disconnect: { id: productId } } },
  });
  revalidatePath(`/iv-manage-84x2/collections/${collectionId}`);
  revalidatePath("/");
  redirect(`/iv-manage-84x2/collections/${collectionId}?success=Product+removed+from+collection.`);
}
