import { NextRequest, NextResponse } from "next/server";
import { getTags } from "@/lib/queries";
import { queryRaw } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";

export async function GET(req: NextRequest) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
  const tags = await getTags();
  return NextResponse.json(tags);
}

export async function POST(req: NextRequest) {
  const user = await getCurrentUser(req);
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
  const { name, color } = await req.json();
  if (!name?.trim()) {
    return NextResponse.json({ error: "name required" }, { status: 400 });
  }
  const rows = await queryRaw<{ id: number; name: string; color: string }>(
    `INSERT INTO tags (name, color) VALUES ($1, $2) RETURNING id, name, color`,
    [name.trim(), color || "#6366f1"]
  );
  return NextResponse.json(rows[0], { status: 201 });
}
