import { NextRequest, NextResponse } from "next/server";
import { queryOne, queryRows } 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();
  const proc = await queryOne(
    `SELECT P.objid AS "OBJID", P.proc_no AS "PROC_NO",
            TO_CHAR(P.proc_date,'YYYY-MM-DD') AS "PROC_DATE",
            P.status AS "STATUS", P.total_amount AS "TOTAL_AMOUNT", P.memo AS "MEMO",
            P.delivery_place  AS "DELIVERY_PLACE",
            P.delivery_period AS "DELIVERY_PERIOD",
            P.payment_terms   AS "PAYMENT_TERMS",
            P.freight_terms   AS "FREIGHT_TERMS",
            V.objid AS "VENDOR_OBJID", V.supply_name AS "VENDOR_NAME"
     FROM momo_procurements P
     LEFT JOIN supply_mng V ON P.vendor_objid = V.objid::text
     WHERE P.objid = $1`,
    [objid]
  );
  if (!proc) return NextResponse.json({ success: false, message: "찾을 수 없습니다." }, { status: 404 });
  const items = await queryRows(
    `SELECT PI.objid AS "OBJID", PI.item_objid AS "ITEM_OBJID",
            I.item_code AS "ITEM_CODE", I.item_name AS "ITEM_NAME", I.unit AS "UNIT",
            PI.qty AS "QTY", PI.cost_price AS "COST_PRICE", PI.total_amount AS "TOTAL_AMOUNT",
            PI.received_qty AS "RECEIVED_QTY",
            PI.received_normal AS "RECEIVED_NORMAL",
            PI.received_defect AS "RECEIVED_DEFECT"
     FROM momo_procurement_items PI
     JOIN momo_items I ON PI.item_objid = I.objid
     WHERE PI.proc_objid = $1
     ORDER BY PI.objid`,
    [objid]
  );
  return NextResponse.json({ success: true, proc, items });
}
