// 매입 입금처리 — 결재상태(입금)만 기록. 진행상태(status)는 건드리지 않는다.
//   결재(입금)와 입고 진행은 독립. paid_date 로 입금완료 표시.
import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { ensureProcPaymentSeparation } from "@/lib/momo-proc";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  await ensureProcPaymentSeparation();

  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; paid_date: string | null }>(
    `SELECT status, total_amount, paid_date FROM momo_procurements WHERE objid::text = $1`,
    [objid]
  );
  if (!proc) return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });
  // 입금 가능 진행상태: 발주요청/입고중/입고완료. (작성중/취소는 불가)
  if (!["REQUESTED", "PARTIAL", "RECEIVED"].includes(proc.status)) {
    return NextResponse.json({ success: false, message: `현재 상태(${proc.status})에서는 입금 처리할 수 없습니다.` }, { status: 400 });
  }
  if (proc.paid_date) {
    return NextResponse.json({ success: false, message: "이미 입금완료된 발주입니다." }, { status: 400 });
  }

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

  // status 는 그대로 두고 결재정보만 채운다.
  await execute(
    `UPDATE momo_procurements
       SET 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 });
}
