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

export async function GET(request: Request) {
  try {
    const accountId = await getActiveAccountId();
    const { where: accountWhere } = await requireUserAccountScope(accountId);
    const topicId = new URL(request.url).searchParams.get("topicId");
    const where = {
      ...accountWhere,
      ...(topicId ? { topicId } : {}),
    };
    const scans = await prisma.scan.findMany({
      where,
      orderBy: { createdAt: "desc" },
      take: 20,
      include: {
        topic: true,
        items: {
          orderBy: [{ combinedScore: "desc" }, { score: "desc" }],
          include: {
            replies: { orderBy: { likeCount: "desc" } },
            outreachTargets: {
              include: { drafts: { orderBy: { createdAt: "desc" } } },
            },
          },
        },
      },
    });

    return NextResponse.json({ scans });
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "讀取海巡紀錄失敗";
    console.error("[scans] GET failed:", error);
    return NextResponse.json({ error: message, scans: [] }, { status: 500 });
  }
}