import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getActiveAccountId } from "@/lib/account-context";
import { apiRouteErrorResponse } from "@/lib/auth/api";
import { requireUserAccountScope } from "@/lib/auth/user-scope";

const PAGE_SIZE = 10;

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const topicId = searchParams.get("topicId");
    const page = Math.max(1, parseInt(searchParams.get("page") ?? "1", 10) || 1);
    const limit = Math.min(50, Math.max(1, parseInt(searchParams.get("limit") ?? String(PAGE_SIZE), 10) || PAGE_SIZE));
    const accountId = await getActiveAccountId();
    const { where: accountWhere } = await requireUserAccountScope(accountId);

    const where = {
      sortOrder: { not: null },
      status: { not: "REJECTED" },
      ...accountWhere,
      ...(topicId ? { topicId } : {}),
    };

    const [drafts, total] = await Promise.all([
      prisma.draft.findMany({
        where,
        orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }],
        skip: (page - 1) * limit,
        take: limit,
      }),
      prisma.draft.count({ where }),
    ]);

    return NextResponse.json({
      rows: drafts,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit) || 1,
    });
  } catch (error) {
    return apiRouteErrorResponse(error, "matrix");
  }
}
