import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } 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 { objid } = await req.json();
  const order = await queryOne<{ customer_objid: string; status: string }>(
    `SELECT customer_objid, status FROM momo_orders WHERE objid = $1`,
    [objid]
  );
  if (!order) return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });
  // 본인 발주 매칭 (user.objid 또는 user.userId 와 customer_objid 일치)
  const userOwn = r.user.objid ?? r.user.userId;
  if (r.user.role === "USER" && order.customer_objid !== userOwn && order.customer_objid !== r.user.userId) {
    return NextResponse.json({ success: false, message: "권한이 없습니다." }, { status: 403 });
  }
  if (order.status !== "REQUESTED") {
    return NextResponse.json({ success: false, message: "요청 상태에서만 취소 가능합니다." }, { status: 400 });
  }
  await execute(`UPDATE momo_orders SET status='CANCELLED', update_date=NOW() WHERE objid=$1`, [objid]);
  return NextResponse.json({ success: true });
}
