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 products = await prisma.product.findMany({
      where: { locale },
      orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }],
    });
    return Response.json(products);
  } catch {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
}

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