import prisma from "@/server/db/prisma";
import { HttpError } from "@/server/http/errors";
import { ok } from "@/server/http/response";
import { parseIdParam } from "@/server/http/schemas";
import { withErrorHandling } from "@/server/http/withErrorHandling";
import { deleteProjectImages } from "@/server/uploads/cleanup";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 300; // 5 minutes

export const GET = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);

    const project = await prisma.project.findUnique({
      where: { id },
    });

    if (!project) throw new HttpError("Project not found", { status: 404 });
    return ok(project);
  },
);

export const PUT = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);
    const formData = await request.formData();

    const name = formData.get("name") as string | null;
    const description = formData.get("description") as string | null;
    const shortDescription = formData.get("shortDescription") as string | null;
    const coverImage = formData.get("coverImage") as string | null;
    const galleryImages = formData.getAll("galleryImages[]") as string[];

    const updates: any = {};
    if (name) updates.name = name;
    if (description) updates.description = description;
    if (shortDescription !== null) updates.shortDescription = shortDescription;
    if (coverImage) updates.coverImage = coverImage;
    if (galleryImages) updates.galleryImages = galleryImages;
    updates.updatedAt = new Date();

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

    const updatedProject = await prisma.project.update({
      where: { id },
      data: updates,
    });
    return ok(updatedProject);
  },
);

export const DELETE = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);

    const project = await prisma.project.findUnique({
      where: { id },
    });
    if (!project) throw new HttpError("Project not found", { status: 404 });

    await prisma.project.delete({
      where: { id },
    });

    // Delete images in parallel (non-blocking, errors are silently ignored)
    await deleteProjectImages(project);

    return ok({ success: true });
  },
);
