"use server";

import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { uploadFile } from "@/lib/upload";

export async function getProducts() {
  return await prisma.product.findMany({
    orderBy: { createdAt: 'desc' }
  });
}

export async function addProduct(formData: FormData) {
  const name = formData.get("name") as string;
  const category = formData.get("category") as string;
  const description = formData.get("description") as string;
  const price = 0;
  
  const file = formData.get("imageFile") as File;
  let image = formData.get("image") as string;
  if (file && file.size > 0) {
    const uploadedUrl = await uploadFile(file);
    if (uploadedUrl) image = uploadedUrl;
  }

  await prisma.product.create({
    data: {
      name,
      category,
      description,
      price: 0, // Removed price from frontend, setting default 0
      image: image || null,
      specs: "[]" // Empty JSON string for now
    }
  });

  revalidatePath("/admin/products");
  revalidatePath("/", "layout");
}

export async function deleteProduct(id: string) {
  await prisma.product.delete({ where: { id } });
  revalidatePath("/admin/products");
  revalidatePath("/");
}
