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

// 1레벨 같은 Part No 중복 체크 (원본: partMng/checkSameTopPartNo.do)
// 1레벨 (parent_objid IS NULL) 에 이미 등록된 part_mng.objid 가 rightCheckedArr 에 있으면 true
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ result: false });

  const body = await request.json();
  const bomReportObjId = String(body.OBJID || body.BOM_REPORT_OBJID || "");
  const rightCheckedArr: string[] = Array.isArray(body.rightCheckedArr)
    ? body.rightCheckedArr.map((s: unknown) => String(s))
    : [];

  if (!bomReportObjId || rightCheckedArr.length === 0) {
    return NextResponse.json({ result: false });
  }

  // 1레벨 기존 part_no (part_mng.objid) 목록
  const existing = await queryRows<{ part_no: string }>(
    `SELECT DISTINCT Q.part_no AS part_no
     FROM bom_part_qty Q
     WHERE Q.bom_report_objid = $1
       AND (Q.parent_objid IS NULL OR Q.parent_objid = '')`,
    [bomReportObjId],
  );
  const existingSet = new Set(existing.map((r) => String(r.part_no)));

  // 기존 1레벨에 rightChecked 중 하나라도 있으면 중복
  // 단순히 part_no (objid) 매칭이 아니라, 실제 동일 PART_NO(문자열) 매칭도 고려해야 함
  const directHit = rightCheckedArr.some((id) => existingSet.has(id));
  if (directHit) return NextResponse.json({ result: true });

  // objid가 달라도 part_no(문자열)가 같으면 중복으로 판정
  if (existing.length > 0 && rightCheckedArr.length > 0) {
    const rows = await queryRows<{ cnt: string }>(
      `SELECT COUNT(*)::text AS cnt FROM part_mng P1
        WHERE P1.objid::text = ANY($1::text[])
          AND EXISTS (
            SELECT 1 FROM part_mng P2
            WHERE P2.objid::text = ANY($2::text[])
              AND P2.part_no = P1.part_no
          )`,
      [rightCheckedArr, existing.map((e) => String(e.part_no))],
    );
    if (Number(rows[0]?.cnt || 0) > 0) return NextResponse.json({ result: true });
  }

  return NextResponse.json({ result: false });
}
