// 빈 발주 생성 — admin 수기 작성용. 즉시 출고관리 화면 안에서 거래처/품목 채워가는 흐름.
// status='REQUESTED', customer 는 admin 본인으로 임시 박음. detail 에서 변경 가능.
import { NextResponse } from "next/server";
import { pool, queryOne } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { getSupplierByBranch } from "@/lib/momo-branches";

export async function POST() {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  const adminId = g.user.objid || g.user.userId;

  const orderObjid = createObjectId();
  const orderNo = await genOrderNo();

  // 기본 supplier — admin 본인 사용자(또는 HQ) 의 기준명세표 snapshot
  // customer 가 바뀌면 별도 API (update-customer) 가 supplier 재계산
  const supplier = await getSupplierByBranch("HQ");

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(
      `INSERT INTO momo_orders (
         objid, order_no, customer_objid, order_date, status,
         total_supply, total_vat, total_amount, total_taxfree, total_taxable,
         total_delivery, total_charter, memo, regdate, regid,
         supplier_branch, supplier_name, supplier_ceo, supplier_bank_account,
         supplier_phone, supplier_email, supplier_biz_no, supplier_address
       ) VALUES ($1, $2, $3, CURRENT_DATE, 'REQUESTED',
                 0, 0, 0, 0, 0, 0, 0, NULL, NOW(), $3,
                 $4, $5, $6, $7, $8, $9, $10, $11)`,
      [orderObjid, orderNo, adminId,
       supplier.CODE, supplier.NAME, supplier.CEO, supplier.BANK_ACCOUNT,
       supplier.PHONE, supplier.EMAIL, supplier.BIZ_NO, supplier.ADDRESS]
    );
    await client.query("COMMIT");
    return NextResponse.json({ success: true, objId: orderObjid, orderNo });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[orders/create-empty]", err);
    return NextResponse.json({ success: false, message: err instanceof Error ? err.message : "오류" }, { status: 500 });
  } finally {
    client.release();
  }
}

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