import { NextResponse } from "next/server";
import { prisma } from "@/core/db/prisma";
import { uploadFileLocally } from "@/core/storage/local";
import { verifySession } from "@/core/security/session";
import { projectSchema } from "@/features/projects/project-schema";
import { revalidatePath } from "next/cache";

export async function PUT(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await verifySession();
  if (!session) {
    return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;

  try {
    const formData = await req.formData();
    
    const data = {
      title: formData.get("title") as string,
      slug: formData.get("slug") as string,
      description: formData.get("description") as string,
      category: formData.get("category") as string,
      repoUrl: formData.get("repoUrl") as string,
      liveUrl: formData.get("liveUrl") as string,
      isPublished: formData.get("isPublished") === "true" || formData.get("isPublished") === "on",
      techStack: formData.get("techStack") as string,
      year: formData.get("year") as string,
      highlights: formData.get("highlights") as string,
    };

    const validation = projectSchema.safeParse(data);
    if (!validation.success) {
      return NextResponse.json({ success: false, message: validation.error.issues[0].message }, { status: 400 });
    }

    // Existing images that should be retained (sent back from client)
    const existingImages = formData.getAll("existingImages") as string[];

    // Handle new images upload
    const imageFiles = formData.getAll("images") as File[];
    const newUploadedUrls: string[] = [];

    for (const file of imageFiles) {
      if (file && file.size > 0 && file.name) {
        try {
          const url = await uploadFileLocally(file);
          newUploadedUrls.push(url);
        } catch (e: any) {
          console.error("Local upload error:", e);
          return NextResponse.json({ success: false, message: "Failed to upload one or more images." }, { status: 500 });
        }
      }
    }

    // Merge: retained existing + newly uploaded
    const allImageUrls = [...existingImages, ...newUploadedUrls];

    const project = await prisma.project.update({
      where: { id },
      data: {
        title: validation.data.title,
        slug: validation.data.slug,
        description: validation.data.description,
        category: validation.data.category,
        repoUrl: validation.data.repoUrl || null,
        liveUrl: validation.data.liveUrl || null,
        isPublished: validation.data.isPublished,
        // First image is cover
        ...(allImageUrls.length > 0 && { imageUrl: allImageUrls[0] }),
        imageUrls: allImageUrls,
        techStack: validation.data.techStack ? validation.data.techStack.split(",").map(s => s.trim()).filter(s => s) : [],
        year: validation.data.year || null,
        highlights: validation.data.highlights ? validation.data.highlights.split(",").map(s => s.trim()).filter(s => s) : [],
      },
    });

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

    return NextResponse.json({ success: true, project });
  } catch (error: any) {
    console.error("API Error (Update Project):", error);
    if (error?.code === "P2002") {
      return NextResponse.json({ success: false, message: "Project slug already exists" }, { status: 400 });
    }
    return NextResponse.json({ success: false, message: "Failed to update project" }, { status: 500 });
  }
}

export async function DELETE(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await verifySession();
  if (!session) {
    return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;

  try {
    await prisma.project.delete({ where: { id } });
    revalidatePath("/admin/dashboard/projects");
    revalidatePath("/admin/dashboard");
    revalidatePath("/");
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ success: false, message: "Failed to delete project" }, { status: 500 });
  }
}
