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

// 재발주 시 원본 발주서 선택용 — 같은 프로젝트의 approvalComplete 된 발주서 목록
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 contractObjId = String(body.contract_mgmt_objid || "");
  if (!contractObjId) return NextResponse.json({ RESULTLIST: [] });

  // 재발주 원본 후보: 같은 프로젝트의 결재완료 건. 동시발주 슬레이브만 제외 (마스터/단일은 선택 가능).
  const rows = await queryRows(
    `SELECT POM.objid::text AS "OBJID",
            POM.purchase_order_no AS "PURCHASE_ORDER_NO",
            POM.title AS "TITLE",
            TO_CHAR(POM.regdate, 'YYYY-MM-DD') AS "REGDATE",
            (SELECT supply_name FROM admin_supply_mng WHERE objid::text = POM.partner_objid LIMIT 1) AS "PARTNER_NAME"
       FROM purchase_order_master POM
      WHERE POM.contract_mgmt_objid::text = $1
        AND POM.status = 'approvalComplete'
        AND NOT (
          COALESCE(POM.multi_yn,'') = 'Y'
          AND COALESCE(POM.multi_master_yn,'') != 'Y'
        )
      ORDER BY POM.regdate DESC
`,
    [contractObjId],
  );
  return NextResponse.json({ RESULTLIST: rows });
}
