// 발주 라인의 비고(remark) 수정 — 관리자 또는 본인.
// REQUESTED 상태에서만 수정 가능. ITEM/DELIVERY/CHARTER 모두 가능.
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { requireMomoUser } from "@/lib/momo-guard";

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

  const body = await req.json().catch(() => ({}));
  const { lineObjid, remark } = body as { lineObjid?: string; remark?: string };
  if (!lineObjid) {
    return NextResponse.json({ success: false, message: "라인 식별자가 필요합니다." }, { status: 400 });
  }

  const isAdmin = r.user.isAdmin || r.user.role === "ADMIN" || r.user.userType === "A";

  // 권한 확인 — 본인 발주이거나 관리자
  const own = await pool.query(
    `SELECT O.customer_objid, O.status
     FROM momo_order_items OI
     JOIN momo_orders O ON O.objid = OI.order_objid
     WHERE OI.objid = $1`,
    [lineObjid]
  );
  if (own.rowCount === 0) {
    return NextResponse.json({ success: false, message: "라인을 찾을 수 없습니다." }, { status: 404 });
  }
  const row = own.rows[0];
  const userOwn = r.user.objid ?? r.user.userId;
  if (!isAdmin && row.customer_objid !== userOwn && row.customer_objid !== r.user.userId) {
    return NextResponse.json({ success: false, message: "권한이 없습니다." }, { status: 403 });
  }
  if (row.status !== "REQUESTED") {
    return NextResponse.json({ success: false, message: "출고 요청 상태에서만 비고를 수정할 수 있습니다." }, { status: 400 });
  }

  await pool.query(
    `UPDATE momo_order_items SET remark = $2 WHERE objid = $1`,
    [lineObjid, (remark ?? "").trim() || null]
  );
  return NextResponse.json({ success: true });
}
