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

// 원본: common.getProjectNameList (contract_objid 동일) + salesMng.salesBomReportInfo2(구매BOM 존재 여부)
// 동시발주 추가 프로젝트 후보 조회:
//   1) 마스터 프로젝트(contract_mgmt_objid)와 동일한 CONTRACT_OBJID(상위 계약) 소속
//   2) 마스터 자신은 제외
//   3) 해당 프로젝트에 구매BOM(sales_bom_report_part)이 등록되어 있어야 함
//   4) (옵션) 선택된 공급처가 구매BOM의 supply_objid/1/2/3/4 중 하나로 등록된 프로젝트만
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 masterProjectObjId = String(body.contract_mgmt_objid || "");
  const partnerObjId = String(body.partner_objid || "");
  if (!masterProjectObjId) return NextResponse.json({ RESULTLIST: [] });

  // partner_objid가 있으면 해당 공급처가 등록된 BOM만, 없으면 BOM 존재 여부만 필터
  const partnerFilter = partnerObjId
    ? `AND EXISTS (
         SELECT 1
           FROM part_bom_report PBR
           JOIN sales_bom_report_part SBP ON SBP.parent_objid::text = PBR.objid::text
          WHERE PBR.contract_objid = P.objid
            AND (SBP.supply_objid = $2 OR SBP.supply_objid1 = $2
              OR SBP.supply_objid2 = $2 OR SBP.supply_objid3 = $2 OR SBP.supply_objid4 = $2)
       )`
    : `AND EXISTS (
         SELECT 1
           FROM part_bom_report PBR
           JOIN sales_bom_report_part SBP ON SBP.parent_objid::text = PBR.objid::text
          WHERE PBR.contract_objid = P.objid
       )`;

  const sql = `
    SELECT P.objid::text AS "OBJID",
           P.project_no AS "PROJECT_NO",
           P.customer_project_name AS "CUSTOMER_PROJECT_NAME",
           COALESCE(P.project_no, '') || ' - ' || COALESCE(P.customer_project_name, '') AS "LABEL"
      FROM project_mgmt P
     WHERE P.contract_objid = (
             SELECT contract_objid FROM project_mgmt WHERE objid::text = $1 LIMIT 1
           )
       AND P.objid::text <> $1
       ${partnerFilter}
     ORDER BY P.project_no
  `;

  const params = partnerObjId ? [masterProjectObjId, partnerObjId] : [masterProjectObjId];
  const rows = await queryRows(sql, params);
  return NextResponse.json({ RESULTLIST: rows });
}
