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

function createMenuId(): number {
  return Math.floor(Math.random() * 2000000000) - 1000000000;
}

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.objid;
  const objid = isNew ? createMenuId() : parseInt(body.objid, 10);
  const client = await pool.connect();
  try {
    if (isNew) {
      await client.query(
        `INSERT INTO menu_info (objid, menu_name_kor, menu_name_eng, menu_url, parent_obj_id, seq, status, writer, regdate)
         VALUES ($1, $2, $3, $4, $5, $6, 'active', $7, now())`,
        [objid, body.menu_name_kor || "", body.menu_name_eng || "",
         body.menu_url || "", parseInt(body.parent_obj_id || "0", 10),
         parseInt(body.seq || "0", 10), user.userId]
      );
    } else {
      await client.query(
        `UPDATE menu_info SET menu_name_kor=$1, menu_name_eng=$2, menu_url=$3, parent_obj_id=$4, seq=$5, status=$6
         WHERE objid=$7`,
        [body.menu_name_kor || "", body.menu_name_eng || "",
         body.menu_url || "", parseInt(body.parent_obj_id || "0", 10),
         parseInt(body.seq || "0", 10), body.status || "active", objid]
      );
    }
    return NextResponse.json({ success: true, message: isNew ? "등록되었습니다." : "수정되었습니다.", objid });
  } catch (e) {
    console.error("Menu save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." });
  } finally { client.release(); }
}
