// 발주 hard delete — admin 만, REQUESTED 상태만 (수기 출고 정리용).
// 출고 처리(APPROVED) 이후는 재고/이력 정합성 때문에 cancel(CANCELED) 흐름 사용.
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 } = await req.json() as { objid?: string };
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const cur = await client.query(`SELECT status FROM momo_orders WHERE objid = $1 FOR UPDATE`, [objid]);
    if (cur.rowCount === 0) {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });
    }
    if (cur.rows[0].status !== "REQUESTED") {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "출고요청 상태만 삭제 가능합니다. 출고된 발주는 취소 처리하세요." }, { status: 400 });
    }
    // 연관 데이터 정리 (REQUESTED 단계라 stock_moves/payments 없음)
    await client.query(`DELETE FROM momo_einvoice_items WHERE einvoice_objid IN (SELECT objid FROM momo_einvoices WHERE order_objid = $1)`, [objid]);
    await client.query(`DELETE FROM momo_einvoices WHERE order_objid = $1`, [objid]);
    await client.query(`DELETE FROM momo_order_items WHERE order_objid = $1`, [objid]);
    await client.query(`DELETE FROM momo_orders WHERE objid = $1`, [objid]);
    await client.query("COMMIT");
    return NextResponse.json({ success: true });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[orders/delete]", err);
    return NextResponse.json({ success: false, message: err instanceof Error ? err.message : "오류" }, { status: 500 });
  } finally {
    client.release();
  }
}
