// 계산서 발행 일괄 처리
import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } 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 { objids } = await req.json();
  if (!Array.isArray(objids) || objids.length === 0) {
    return NextResponse.json({ success: false, message: "발행할 항목이 없습니다." }, { status: 400 });
  }
  const today = new Date();
  const ym = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, "0")}`;
  const prefix = `INV-${ym}-`;
  const last = await queryOne<{ MAX_NO: string }>(
    `SELECT COALESCE(MAX(invoice_no),'') AS "MAX_NO" FROM momo_orders WHERE invoice_no LIKE $1 || '%'`,
    [prefix]
  );
  let lastNum = last?.MAX_NO ? Number(last.MAX_NO.replace(prefix, "")) || 0 : 0;

  for (const id of objids) {
    lastNum++;
    const invNo = prefix + String(lastNum).padStart(4, "0");
    await execute(
      `UPDATE momo_orders
         SET status='INVOICED', invoice_no=$2, invoice_date=CURRENT_DATE, update_date=NOW()
       WHERE objid=$1 AND status IN ('APPROVED','PAID')`,
      [id, invNo]
    );
  }
  return NextResponse.json({ success: true, count: objids.length });
}
