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

// 경비신청 저장 (saveExpense 대응, 단순화)
// body: { actionType, expense_master_objid?, project_mgmt_objid, bus_title, bns_start_date, bns_end_date,
//         exp_area_cd, exp_status_cd, bus_content, reason, amount_payment, status }
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const isNew = body.actionType === "regist" || !body.expense_master_objid;
  const objId = isNew ? createObjectId() : String(body.expense_master_objid);
  const projectMgmtObjid = String(body.project_mgmt_objid || "").trim() || "0";

  try {
    // expense_master의 많은 컬럼이 'null::character varying' 기본값이라
    // 명시적으로 빈 문자열 전달 필요
    await execute(
      `INSERT INTO expense_master (
         expense_master_objid, project_mgmt_objid, expense_id,
         bus_title, bns_start_date, bns_end_date,
         exp_status_cd, exp_company_cd, exp_area_cd,
         vehicel_used, bus_users_id, bus_content, reason, instructions,
         amount_payment, reg_user_id, reg_date, exp_sort_cd, status
       ) VALUES ($1,$2,'',$3,$4,$5,$6,'',$7,'',$8,$9,$10,'',$11,$12,TO_CHAR(NOW(),'YYYY-MM-DD'),'',$13)
       ON CONFLICT (expense_master_objid) DO UPDATE SET
         project_mgmt_objid = EXCLUDED.project_mgmt_objid,
         bus_title = EXCLUDED.bus_title,
         bns_start_date = EXCLUDED.bns_start_date,
         bns_end_date = EXCLUDED.bns_end_date,
         exp_status_cd = EXCLUDED.exp_status_cd,
         exp_area_cd = EXCLUDED.exp_area_cd,
         bus_content = EXCLUDED.bus_content,
         reason = EXCLUDED.reason,
         amount_payment = EXCLUDED.amount_payment`,
      [
        objId, projectMgmtObjid,
        body.bus_title || "", body.bns_start_date || "", body.bns_end_date || "",
        body.exp_status_cd || "", body.exp_area_cd || "",
        body.bus_users_id || user.userId, body.bus_content || "", body.reason || "",
        body.amount_payment || "", user.userId, body.status || "created",
      ]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (error) {
    console.error("Expense save:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
