// 빈 매입 발주서 생성 — 좌-우 분할 화면에서 [+ 새 발주] 누를 때 사용
import { NextRequest, NextResponse } from "next/server";
import { pool, queryOne } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  const body = await req.json().catch(() => ({}));
  const { vendorObjid, memo } = body as { vendorObjid?: string; memo?: string };

  const procObjid = createObjectId();
  const procNo = await genProcNo();
  await pool.query(
    `INSERT INTO momo_procurements (objid, proc_no, vendor_objid, proc_date, status, total_amount, memo, regdate)
     VALUES ($1, $2, $3, CURRENT_DATE, 'OPEN', 0, $4, NOW())`,
    [procObjid, procNo, vendorObjid ?? null, memo ?? null]
  );
  return NextResponse.json({ success: true, objId: procObjid, procNo });
}

async function genProcNo(): Promise<string> {
  const today = new Date();
  const ymd = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, "0")}${String(today.getDate()).padStart(2, "0")}`;
  const prefix = `PRC-${ymd}-`;
  const row = await queryOne<{ MAX_NO: string }>(
    `SELECT COALESCE(MAX(proc_no), '') AS "MAX_NO" FROM momo_procurements WHERE proc_no LIKE $1 || '%'`,
    [prefix]
  );
  const lastNum = row?.MAX_NO ? Number(row.MAX_NO.replace(prefix, "")) || 0 : 0;
  return prefix + String(lastNum + 1).padStart(4, "0");
}
