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 POST(req: Request) {
  const session = await verifySession();
  if (!session) {
    return NextResponse.json({ success: false, message: "Unauthorized" }, { status: 401 });
  }

  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 });
    }

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

    for (const file of imageFiles) {
      if (file && file.size > 0 && file.name) {
        try {
          const url = await uploadFileLocally(file);
          uploadedUrls.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 });
        }
      }
    }

    const project = await prisma.project.create({
      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 becomes the cover (backward compat)
        imageUrl: uploadedUrls[0] || undefined,
        imageUrls: uploadedUrls,
        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 (Create 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 create project" }, { status: 500 });
  }
}
