// 매입 입금처리 — procurement 의 status 를 PAID 로 변경하고 paid_* 컬럼 채움
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 body = await req.json().catch(() => ({}));
  const { objid, amount, method, memo } = body as {
    objid?: string; amount?: number; method?: string; memo?: string;
  };
  if (!objid) {
    return NextResponse.json({ success: false, message: "objid 필수" }, { status: 400 });
  }

  const proc = await queryOne<{ status: string; total_amount: number }>(
    `SELECT status, total_amount FROM momo_procurements WHERE objid::text = $1`,
    [objid]
  );
  if (!proc) return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });
  if (proc.status !== "REQUESTED") {
    return NextResponse.json({ success: false, message: `현재 상태(${proc.status})에서는 입금 처리할 수 없습니다.` }, { status: 400 });
  }

  const paidAmount = Number(amount) > 0 ? Number(amount) : Number(proc.total_amount);

  await execute(
    `UPDATE momo_procurements
       SET status      = 'PAID',
           paid_date   = NOW(),
           paid_amount = $1,
           paid_method = $2,
           paid_memo   = $3
     WHERE objid::text = $4`,
    [paidAmount, method || null, memo || null, objid]
  );

  return NextResponse.json({ success: true });
}
