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";

export async function GET(request: Request) {
  try {
    const accountId = await getActiveAccountId();
    const { where } = await requireUserAccountScope(accountId);
    const { searchParams } = new URL(request.url);
    const page = Math.max(1, Number.parseInt(searchParams.get("page") ?? "1", 10) || 1);
    const limit = Math.min(30, Math.max(5, Number.parseInt(searchParams.get("limit") ?? "10", 10) || 10));
    const targetWhere = { scanItem: { scan: { ...where, scanGoal: "placement" } } };
    const [targets, total] = await Promise.all([
      prisma.outreachTarget.findMany({
        where: targetWhere,
        orderBy: { createdAt: "desc" },
        include: {
          scanItem: { include: { scan: { include: { topic: true } }, replies: true } },
          drafts: { orderBy: { createdAt: "desc" } },
        },
        skip: (page - 1) * limit,
        take: limit,
      }),
      prisma.outreachTarget.count({ where: targetWhere }),
    ]);

    return NextResponse.json({
      targets,
      page,
      limit,
      total,
      totalPages: Math.max(1, Math.ceil(total / limit)),
    });
  } catch (error) {
    return apiRouteErrorResponse(error, "outreach");
  }
}
