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

// 경비신청서 저장 (mergeExpenseMaster 대응)
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.objId || body.actionType === "regist";
  const objId = isNew ? createObjectId() : body.objId;

  const client = await pool.connect();
  try {
    // 신규시 expense_id 자동 생성: EC-YYYY-NNN
    let expenseId = body.expense_id || "";
    if (isNew && !expenseId) {
      const year = new Date().getFullYear();
      const r = await client.query(
        `SELECT COALESCE(MAX(SUBSTR(expense_id, 9)::numeric), 0)::int + 1 AS seq
         FROM expense_master WHERE expense_id LIKE $1`, [`EC-${year}-%`]
      );
      const seq = r.rows[0]?.seq || 1;
      expenseId = `EC-${year}-${String(seq).padStart(3, "0")}`;
    }

    await client.query(
      `INSERT INTO expense_master (
        expense_master_objid, expense_id, project_mgmt_objid,
        bns_start_date, bns_end_date, exp_status_cd, exp_sort_cd,
        exp_area_cd, bus_title, bus_content, vehicel_used, amount_payment,
        reg_user_id, reg_date, status
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, now(), $14)
      ON CONFLICT (expense_master_objid) DO UPDATE SET
        project_mgmt_objid=EXCLUDED.project_mgmt_objid,
        bns_start_date=EXCLUDED.bns_start_date, bns_end_date=EXCLUDED.bns_end_date,
        exp_status_cd=EXCLUDED.exp_status_cd, exp_sort_cd=EXCLUDED.exp_sort_cd,
        exp_area_cd=EXCLUDED.exp_area_cd, bus_title=EXCLUDED.bus_title,
        bus_content=EXCLUDED.bus_content, vehicel_used=EXCLUDED.vehicel_used,
        amount_payment=EXCLUDED.amount_payment, status=EXCLUDED.status`,
      [objId, expenseId, body.project_mgmt_objid || "",
       body.bns_start_date || null, body.bns_end_date || null,
       body.exp_status_cd || "", body.exp_sort_cd || "",
       body.exp_area_cd || "", body.bus_title || "", body.bus_content || "",
       body.vehicel_used || "", body.amount_payment || "0",
       user.userId, body.status || "created"]
    );
    return NextResponse.json({ success: true, objId, expenseId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("Expense save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
