import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";

export async function GET() {
  const posts = await prisma.blogPost.findMany({
    include: { category: true, author: true },
    orderBy: { createdAt: "desc" },
  });
  return NextResponse.json(posts);
}

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await request.json();
  const post = await prisma.blogPost.create({
    data: {
      slugId: body.slugId,
      slugEn: body.slugEn,
      titleId: body.titleId,
      titleEn: body.titleEn,
      excerptId: body.excerptId,
      excerptEn: body.excerptEn,
      contentId: body.contentId,
      contentEn: body.contentEn,
      featuredImage: body.featuredImage,
      authorId: body.authorId,
      categoryId: body.categoryId,
      isPublished: body.isPublished ?? false,
    },
  });
  return NextResponse.json(post, { status: 201 });
}
