// 입금 등록 — 출고완료 → 입금완료 전환
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 { objid, paidAmount, paidDate } = await req.json();
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const order = await queryOne<{ status: string; total_amount: string }>(
    `SELECT status, total_amount FROM momo_orders WHERE objid=$1`,
    [objid]
  );
  if (!order) return NextResponse.json({ success: false, message: "주문 없음" }, { status: 404 });

  const total = Number(order.total_amount);
  const paid = paidAmount != null ? Number(paidAmount) : total;
  // 완납이면 PAID, 부분입금이면 그대로 APPROVED 유지
  const newStatus = paid >= total ? "PAID" : order.status;

  await execute(
    `UPDATE momo_orders SET paid_amount = $2, paid_date = COALESCE($3::date, CURRENT_DATE), status = $4, update_date = NOW() WHERE objid = $1`,
    [objid, paid, paidDate ?? null, newStatus]
  );
  return NextResponse.json({ success: true, status: newStatus });
}
