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

interface Params { params: Promise<{ id: string }> }

export async function GET(_req: NextRequest, { params }: Params) {
  try {
    await requireAuth();
    const { id } = await params;
    const post = await prisma.post.findUnique({
      where: { id },
      include: { tags: { include: { tag: true } } },
    });
    if (!post) return Response.json({ error: "Not found" }, { status: 404 });
    return Response.json(post);
  } catch {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
}

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

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

export async function DELETE(_req: NextRequest, { params }: Params) {
  try {
    await requireAuth();
    const { id } = await params;
    await prisma.post.delete({ where: { id } });
    return Response.json({ success: true });
  } catch (err) {
    console.error("[posts/DELETE]", err);
    return Response.json({ error: "Server error" }, { status: 500 });
  }
}
