// 발주일자(order_date) 변경 — admin 만, REQUESTED/APPROVED 만 허용.
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 { objid, orderDate } = await req.json() as { objid?: string; orderDate?: string };
  if (!objid || !orderDate) {
    return NextResponse.json({ success: false, message: "필수 항목 누락" }, { status: 400 });
  }
  if (!/^\d{4}-\d{2}-\d{2}$/.test(orderDate)) {
    return NextResponse.json({ success: false, message: "날짜 형식이 올바르지 않습니다 (YYYY-MM-DD)." }, { status: 400 });
  }

  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 order_date = $2::date, update_date = NOW() WHERE objid = $1`,
    [objid, orderDate]
  );
  return NextResponse.json({ success: true });
}
