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 posts = await prisma.post.findMany({
      where: { locale },
      include: { tags: { include: { tag: true } } },
      orderBy: { publishedAt: "desc" },
    });
    return Response.json(posts);
  } catch {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
}

export async function POST(req: NextRequest) {
  try {
    await requireAuth();
    const body = await req.json();
    const { tagIds, ...data } = body;

    const post = await prisma.post.create({
      data: {
        ...data,
        tags: tagIds?.length
          ? { create: tagIds.map((id: string) => ({ tagId: id })) }
          : undefined,
      },
      include: { tags: { include: { tag: true } } },
    });
    return Response.json(post, { status: 201 });
  } catch (err) {
    console.error("[posts/POST]", err);
    return Response.json({ error: "Server error" }, { status: 500 });
  }
}
