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

// 권한그룹의 메뉴 ON/OFF 토글
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const { masterObjid, menuObjid, on } = body as { masterObjid: string; menuObjid: string; on: boolean };
  if (!masterObjid || !menuObjid) {
    return NextResponse.json({ success: false, message: "필수 파라미터 누락" }, { status: 400 });
  }

  try {
    if (on) {
      const objid = createObjectId();
      await execute(
        `INSERT INTO authority_sub_menu (objid, master_objid, menu_objid, writer, regdate)
         SELECT $1::numeric, $2::numeric, $3::numeric, $4::text, now()
         WHERE NOT EXISTS (
           SELECT 1 FROM authority_sub_menu WHERE master_objid=$2::numeric AND menu_objid=$3::numeric
         )`,
        [objid, masterObjid, menuObjid, user.userId]
      );
    } else {
      await execute(
        `DELETE FROM authority_sub_menu WHERE master_objid=$1::numeric AND menu_objid=$2::numeric`,
        [masterObjid, menuObjid]
      );
    }
    return NextResponse.json({ success: true });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[auth/menus/toggle]", msg);
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  }
}
