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

// 권한그룹 삭제 (deleteAuthGroup + deleteAuthGroupMember 대응)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  try {
    const body = await request.json();
    const objid = body.objid;
    if (!objid) return NextResponse.json({ success: false, message: "OBJID가 필요합니다." }, { status: 400 });

    // 소속 사용자 먼저 삭제
    await execute(`DELETE FROM AUTHORITY_SUB_USER WHERE MASTER_OBJID = $1::numeric`, [objid]);
    // 메뉴 권한 매핑 삭제
    await execute(`DELETE FROM REL_MENU_AUTH WHERE AUTH_OBJID = $1::numeric`, [objid]);
    // 권한그룹 삭제
    await execute(`DELETE FROM AUTHORITY_MASTER WHERE OBJID = $1::numeric`, [objid]);

    return NextResponse.json({ success: true, message: "삭제되었습니다." });
  } catch (error) {
    console.error("Auth delete:", error);
    return NextResponse.json({ success: false, message: "처리 중 오류가 발생했습니다." }, { status: 500 });
  }
}
