// 발주의 거래처 변경 — admin 전용, REQUESTED 또는 APPROVED 상태만.
// 변경 시 supplier_branch snapshot 도 새 거래처의 기준 명세표로 재계산.
import { NextRequest, NextResponse } from "next/server";
import { pool, queryOne } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { getSupplierByBranch } from "@/lib/momo-branches";

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

  const { objid, customerObjid } = await req.json() as { objid?: string; customerObjid?: string };
  if (!objid || !customerObjid) {
    return NextResponse.json({ success: false, message: "필수 항목 누락" }, { status: 400 });
  }

  // 거래처 존재 + statement_branch 조회
  const cust = await queryOne<{ statement_branch: string | null }>(
    `SELECT COALESCE(statement_branch, 'HQ') AS statement_branch FROM user_info WHERE user_id = $1`,
    [customerObjid]
  );
  if (!cust) {
    return NextResponse.json({ success: false, message: "거래처를 찾을 수 없습니다." }, { status: 404 });
  }
  const supplier = await getSupplierByBranch(cust.statement_branch ?? "HQ");

  const cur = await pool.query(`SELECT status FROM momo_orders WHERE objid = $1`, [objid]);
  if (cur.rowCount === 0) return NextResponse.json({ success: false, message: "발주 없음" }, { status: 404 });
  if (!["REQUESTED", "APPROVED"].includes(cur.rows[0].status)) {
    return NextResponse.json({ success: false, message: "입금 전 발주만 거래처 변경 가능합니다." }, { status: 400 });
  }

  await pool.query(
    `UPDATE momo_orders SET
       customer_objid = $2,
       supplier_branch = $3, supplier_name = $4, supplier_ceo = $5, supplier_bank_account = $6,
       supplier_phone = $7, supplier_email = $8, supplier_biz_no = $9, supplier_address = $10,
       update_date = NOW()
     WHERE objid = $1`,
    [objid, customerObjid,
     supplier.CODE, supplier.NAME, supplier.CEO, supplier.BANK_ACCOUNT,
     supplier.PHONE, supplier.EMAIL, supplier.BIZ_NO, supplier.ADDRESS]
  );
  return NextResponse.json({ success: true });
}
