import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// 검사 체크리스트 행들의 파일 개수 일괄 조회
// body: { objIds: string[] } → { counts: { [objId]: number } }
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const objIds: string[] = Array.isArray(body.objIds) ? body.objIds.map(String).filter(Boolean) : [];
  if (objIds.length === 0) return NextResponse.json({ counts: {} });

  const placeholders = objIds.map((_, i) => `$${i + 1}`).join(",");
  const rows = await queryRows<{ TARGET: string; CNT: string }>(
    `SELECT target_objid AS "TARGET", COUNT(1)::text AS "CNT"
       FROM attach_file_info
      WHERE target_objid IN (${placeholders})
        AND doc_type = 'INSPECTION_CHECKLIST_FILE'
        AND UPPER(COALESCE(status,'')) = 'ACTIVE'
      GROUP BY target_objid`,
    objIds,
  );
  const counts: Record<string, number> = {};
  for (const id of objIds) counts[id] = 0;
  for (const r of rows) counts[String(r.TARGET)] = Number(r.CNT) || 0;
  return NextResponse.json({ counts });
}
