import { NextRequest, NextResponse } from "next/server";
import { execute, pool, queryOne } from "@/lib/db";
import { requireMomoUser } from "@/lib/momo-guard";

let lockColsEnsured = false;
async function ensureLockCols() {
  if (lockColsEnsured) return;
  try {
    await pool.query(`
      ALTER TABLE momo_orders
        ADD COLUMN IF NOT EXISTS editing_by TEXT,
        ADD COLUMN IF NOT EXISTS editing_at TIMESTAMP;
    `);
    lockColsEnsured = true;
  } catch { /* ignore */ }
}

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

  const { objid } = await req.json();
  const order = await queryOne<{ customer_objid: string; status: string; editing_by: string | null; lock_alive: boolean }>(
    `SELECT customer_objid, status, editing_by,
            (editing_at IS NOT NULL AND editing_at > NOW() - INTERVAL '2 minutes') AS lock_alive
       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 });
  }
  // 편집 락 체크 — 다른 사람이 락 보유 중이면 취소 불가
  const myId = String(r.user.objid || r.user.userId);
  if (order.lock_alive && order.editing_by && order.editing_by !== myId) {
    const lockName = await queryOne<{ user_name: string }>(
      `SELECT user_name FROM user_info WHERE user_id = $1`, [order.editing_by]
    );
    const name = lockName?.user_name || order.editing_by;
    return NextResponse.json({
      success: false, locked: true,
      message: `${name} 담당자가 수정 중입니다. 잠시 후 다시 시도하세요.`,
    }, { status: 409 });
  }
  await execute(`UPDATE momo_orders SET status='CANCELLED', update_date=NOW() WHERE objid=$1`, [objid]);
  return NextResponse.json({ success: true });
}
