import { type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/auth";

export async function GET(req: NextRequest) {
  try {
    await requireAuth();
    const locale = req.nextUrl.searchParams.get("locale") ?? "fa";
    const projects = await prisma.project.findMany({
      where: { locale },
      orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }],
    });
    return Response.json(projects);
  } catch {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
}

export async function POST(req: NextRequest) {
  try {
    await requireAuth();
    const body = await req.json();
    const project = await prisma.project.create({ data: body });
    return Response.json(project, { status: 201 });
  } catch (err) {
    console.error("[projects/POST]", err);
    return Response.json({ error: "Server error" }, { status: 500 });
  }
}
