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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const post = await prisma.blogPost.findUnique({
    where: { id },
    include: { category: true, author: true },
  });
  if (!post) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json(post);
}

export async function PUT(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const body = await request.json();
  const post = await prisma.blogPost.update({
    where: { id },
    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,
      categoryId: body.categoryId,
      isPublished: body.isPublished,
      publishedAt: body.isPublished ? new Date() : null,
    },
  });
  return NextResponse.json(post);
}

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  await prisma.blogPost.delete({ where: { id } });
  return NextResponse.json({ success: true });
}
