import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";

/**
 * POST /api/track/view
 * body: { slug: string }
 *
 * Fire-and-forget view counter. Increments Article.viewCount and updates
 * lastViewedAt. Returns 204 No Content as fast as possible — the caller
 * (a beacon from the article page) doesn't need a response body.
 */
export const runtime = "nodejs";

export async function POST(req: Request) {
  let body: { slug?: string };
  try {
    body = (await req.json()) as { slug?: string };
  } catch {
    return new NextResponse(null, { status: 400 });
  }
  const slug = String(body.slug ?? "").trim();
  if (!slug || slug.length > 200) return new NextResponse(null, { status: 400 });

  // Don't await — let it run in the background
  prisma.article
    .update({
      where: { slug },
      data: { viewCount: { increment: 1 } },
    })
    .catch(() => {
      // article may have been deleted — ignore
    });

  return new NextResponse(null, { status: 204 });
}
