import { NextRequest, NextResponse } from "next/server";
import { queryOne, queryRows } 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 EM.expense_master_objid::text AS "OBJID", EM.expense_id AS "EXPENSE_ID",
       EM.project_mgmt_objid AS "PROJECT_MGMT_OBJID", EM.bns_start_date AS "BNS_START_DATE",
       EM.bns_end_date AS "BNS_END_DATE", EM.exp_status_cd AS "EXP_STATUS_CD",
       EM.exp_sort_cd AS "EXP_SORT_CD", EM.exp_area_cd AS "EXP_AREA_CD",
       EM.bus_title AS "BUS_TITLE", EM.bus_content AS "BUS_CONTENT",
       EM.vehicel_used AS "VEHICEL_USED", EM.amount_payment AS "AMOUNT_PAYMENT",
       EM.status AS "STATUS",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = EM.reg_user_id LIMIT 1), '') AS "REG_USER_NAME",
       CM.contract_no AS "PROJECT_NO", CM.project_name AS "PROJECT_NAME"
     FROM expense_master EM
     LEFT JOIN contract_mgmt CM ON CM.objid::text = EM.project_mgmt_objid
     WHERE EM.expense_master_objid::text = $1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  const details = await queryRows(
    `SELECT ED.expense_detail_objid::text AS "OBJID",
       ED.exp_sort_cd AS "EXP_SORT_CD", ED.exp_subm_cd AS "EXP_SUBM_CD",
       ED.exp_subd_cd AS "EXP_SUBD_CD",
       ED.card_used AS "CARD_USED", ED.cash_used AS "CASH_USED", ED.payment AS "PAYMENT"
     FROM expense_detail ED WHERE ED.expense_master_objid::text = $1`, [objId]
  );

  return NextResponse.json({ success: true, data: info, DETAILS: details });
}
