import { z } from "zod";
import prisma from "@/server/db/prisma";
import { ok } from "@/server/http/response";
import { withErrorHandling } from "@/server/http/withErrorHandling";

// POST: Create a new project
const ProjectCreateSchema = z.object({
  name: z.string().min(1),
  description: z.string().min(1),
  shortDescription: z.string().optional(),
  coverImage: z.string().optional().default(""),
  galleryImages: z.array(z.string()).default([]),
});

export const POST = withErrorHandling(async (request: Request) => {
  const formData = await request.formData();
  const parsed = ProjectCreateSchema.parse({
    name: formData.get("name"),
    description: formData.get("description"),
    shortDescription: formData.get("shortDescription") ?? undefined,
    coverImage: formData.get("coverImage") ?? "",
    galleryImages: formData.getAll("galleryImages"),
  });

  const newProject = await prisma.project.create({
    data: {
      name: parsed.name,
      description: parsed.description,
      shortDescription: parsed.shortDescription || null,
      coverImage: parsed.coverImage,
      galleryImages: parsed.galleryImages,
      updatedAt: new Date(),
    },
  });

  return ok(newProject);
});

// GET: Fetch all projects
export const GET = withErrorHandling(async () => {
  const projects = await prisma.project.findMany({
    orderBy: { id: "desc" },
  });
  return ok(projects);
});

// DELETE: Use /api/projects/[id] instead
