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

export async function GET() {
  try {
    await requireAuth();
    const tags = await prisma.tag.findMany({ orderBy: { title: "asc" } });
    return Response.json(tags);
  } catch {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
}

export async function POST(req: NextRequest) {
  try {
    await requireAuth();
    const { title, slug } = await req.json();
    const tag = await prisma.tag.upsert({
      where: { slug },
      create: { title, slug },
      update: { title },
    });
    return Response.json(tag, { status: 201 });
  } catch (err) {
    console.error("[tags/POST]", err);
    return Response.json({ error: "Server error" }, { status: 500 });
  }
}
