// 매입 발주서 삭제 — OPEN(작성중) 상태만 허용. 신청/입고/입금된 발주는 삭제 금지.
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;

  let objid: string;
  try {
    const body = await req.json() as { objid?: string };
    if (!body.objid) throw new Error("objid 누락");
    objid = body.objid;
  } catch {
    return NextResponse.json({ success: false, message: "잘못된 요청입니다." }, { status: 400 });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const cur = await client.query(`SELECT status FROM momo_procurements 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 !== "OPEN") {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "작성중 상태의 발주서만 삭제할 수 있습니다." }, { status: 400 });
    }
    await client.query(`DELETE FROM momo_procurement_items WHERE proc_objid = $1`, [objid]);
    await client.query(`DELETE FROM momo_procurements WHERE objid = $1`, [objid]);
    await client.query("COMMIT");
    return NextResponse.json({ success: true });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[procurements/delete]", err);
    return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
