// 매입 발주서 헤더 (공급업체/메모) 수정 — OPEN/REQUESTED 상태만
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;

  const body = await req.json().catch(() => ({}));
  const { objid, vendorObjid, memo, deliveryPlace, deliveryPeriod, paymentTerms, freightTerms } = body as {
    objid?: string; vendorObjid?: string | null; memo?: string;
    deliveryPlace?: string; deliveryPeriod?: string; paymentTerms?: string; freightTerms?: string;
  };
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const cur = await pool.query(`SELECT status FROM momo_procurements WHERE objid = $1`, [objid]);
  if (cur.rowCount === 0) return NextResponse.json({ success: false, message: "찾을 수 없음" }, { status: 404 });
  const status = cur.rows[0].status;
  if (status !== "OPEN" && status !== "REQUESTED") {
    return NextResponse.json({ success: false, message: "작성/요청 상태에서만 수정 가능" }, { status: 400 });
  }

  const sets: string[] = [];
  const params: unknown[] = [objid];
  let i = 2;
  if (vendorObjid    !== undefined) { sets.push(`vendor_objid    = $${i++}`); params.push(vendorObjid); }
  if (memo           !== undefined) { sets.push(`memo            = $${i++}`); params.push(memo); }
  if (deliveryPlace  !== undefined) { sets.push(`delivery_place  = $${i++}`); params.push(deliveryPlace); }
  if (deliveryPeriod !== undefined) { sets.push(`delivery_period = $${i++}`); params.push(deliveryPeriod); }
  if (paymentTerms   !== undefined) { sets.push(`payment_terms   = $${i++}`); params.push(paymentTerms); }
  if (freightTerms   !== undefined) { sets.push(`freight_terms   = $${i++}`); params.push(freightTerms); }
  if (sets.length === 0) return NextResponse.json({ success: true });

  await pool.query(`UPDATE momo_procurements SET ${sets.join(", ")} WHERE objid = $1`, params);
  return NextResponse.json({ success: true });
}
