import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/currentUser";
import { isEntitled } from "@/lib/entitlement";
import { signR2Url } from "@/lib/r2Sign";

export async function POST(req: NextRequest) {
  const { chapterId } = await req.json();
  if (!chapterId)
    return NextResponse.json({ error: "chapterId required" }, { status: 400 });

  const chapter = await prisma.chapter.findUnique({ where: { id: Number(chapterId) } });
  if (!chapter) return NextResponse.json({ error: "Not found" }, { status: 404 });

  if (!chapter.isPreview) {
    const me = getCurrentUser();
    if (!me) return NextResponse.json({ error: "Sign in required" }, { status: 401 });
    const ok = await isEntitled(me.uid);
    if (!ok) return NextResponse.json({ error: "Subscription required" }, { status: 403 });
  }

  const url = await signR2Url(chapter.hlsKey);
  return NextResponse.json({ url });
}
