"use server";

import { prisma } from "@/lib/prisma";
import { uploadBuffer } from "@/lib/cloudinary";
import { revalidatePath } from "next/cache";

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

export async function createProject(formData: FormData) {
  const title = formData.get("title") as string;
  const year = formData.get("year") as string;
  const location = formData.get("location") as string;
  const category = formData.get("category") as string;
  const description = formData.get("description") as string;
  
  const mainImageFile = formData.get("image") as File;
  const galleryFiles = formData.getAll("gallery") as File[];

  const slug = title.toLowerCase().replace(/ /g, "-").replace(/[^\w-]+/g, "");

  let imageUrl = "";
  let galleryUrls: string[] = [];

  if (mainImageFile && mainImageFile.size > 0) {
    const buffer = Buffer.from(await mainImageFile.arrayBuffer());
    imageUrl = await uploadBuffer(buffer, slug);
  }

  for (const file of galleryFiles) {
    if (file && file.size > 0) {
      const buffer = Buffer.from(await file.arrayBuffer());
      const url = await uploadBuffer(buffer, slug);
      galleryUrls.push(url);
    }
  }

  await prisma.project.create({
    data: {
      title,
      year,
      location,
      category,
      description,
      slug,
      image: imageUrl,
      gallery: galleryUrls
    }
  });

  revalidatePath("/admin/projects");
  revalidatePath("/projects");
  revalidatePath("/");
}

export async function updateProject(id: number, formData: FormData) {
  const title = formData.get("title") as string;
  const year = formData.get("year") as string;
  const location = formData.get("location") as string;
  const category = formData.get("category") as string;
  const description = formData.get("description") as string;
  const keepGalleryJson = formData.get("keepGallery") as string;
  
  const mainImageFile = formData.get("image") as File;
  const galleryFiles = formData.getAll("gallery") as File[];

  const existingProject = await prisma.project.findUnique({ where: { id } });
  if (!existingProject) throw new Error("Project not found");

  const slug = title.toLowerCase().replace(/ /g, "-").replace(/[^\w-]+/g, "");

  const existingCover = formData.get("existingCover") as string;
  let imageUrl = existingCover || ""; // Use existing if provided, else empty
  
  // Parse existing gallery images we want to keep
  let galleryUrls: string[] = keepGalleryJson ? JSON.parse(keepGalleryJson) : [...existingProject.gallery];

  // Update Main Image if new file uploaded
  if (mainImageFile && mainImageFile.size > 0) {
    const buffer = Buffer.from(await mainImageFile.arrayBuffer());
    imageUrl = await uploadBuffer(buffer, slug);
  }

  // Add New Gallery Images if any
  for (const file of galleryFiles) {
    if (file && file.size > 0) {
      const buffer = Buffer.from(await file.arrayBuffer());
      const url = await uploadBuffer(buffer, slug);
      galleryUrls.push(url);
    }
  }

  await prisma.project.update({
    where: { id },
    data: {
      title,
      year,
      location,
      category,
      description,
      slug,
      image: imageUrl,
      gallery: galleryUrls
    }
  });

  revalidatePath("/admin/projects");
  revalidatePath("/projects");
  revalidatePath("/");
}

export async function deleteProject(id: number) {
  await prisma.project.delete({
    where: { id }
  });
  revalidatePath("/admin/projects");
  revalidatePath("/projects");
  revalidatePath("/");
}
