import { NextRequest, NextResponse } from "next/server";
import { queryOne } from "@/lib/db";
import { getSession } from "@/lib/session";

export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });
  const { objId } = await request.json();
  if (!objId) return NextResponse.json({ success: false, message: "objId required" });

  const info = await queryOne(
    `SELECT IM.objid::text AS "OBJID",
       IM.objid::text AS "PAYMENT_NO", IM.parent_objid AS "PARENT_OBJID",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "SUPPLIER_NAME",
       CM.contract_no AS "PROJECT_NO",
       IM.issuance_date AS "PAYMENT_DATE",
       COALESCE(IM.price_sum::numeric, 0) AS "PAYMENT_AMOUNT",
       POM.payment_terms AS "PAYMENT_TYPE", IM.status AS "STATUS",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = IM.writer LIMIT 1), '') AS "WRITER_NAME"
     FROM invoice_mgmt IM
     LEFT JOIN purchase_order_master POM ON POM.objid::text = IM.parent_objid
     LEFT JOIN contract_mgmt CM ON CM.objid = POM.contract_mgmt_objid
     WHERE IM.objid::text = $1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });
  return NextResponse.json({ success: true, data: info });
}
