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

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 { objid, cascade } = body as { objid?: string | number; cascade?: boolean };
  if (!objid) return NextResponse.json({ success: false, message: "삭제할 메뉴를 선택하세요." });

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const target = Number(objid);

    const descendants = await client.query<{ objid: number }>(
      `WITH RECURSIVE tree AS (
         SELECT objid FROM menu_info WHERE objid = $1
         UNION ALL
         SELECT m.objid FROM menu_info m JOIN tree t ON m.parent_obj_id = t.objid
       )
       SELECT objid FROM tree`,
      [target]
    );
    const ids = descendants.rows.map((r) => r.objid);
    const childCount = ids.length - 1;

    if (childCount > 0 && !cascade) {
      await client.query("ROLLBACK");
      return NextResponse.json({
        success: false,
        message: `하위 메뉴 ${childCount}개가 있습니다. 함께 삭제하려면 다시 시도하세요.`,
        childCount, needsCascade: true,
      });
    }

    // rel_menu_auth 의 정확한 컬럼은 menu_objid (언더스코어 없음)
    await client.query(`DELETE FROM rel_menu_auth WHERE menu_objid = ANY($1::bigint[])`, [ids]);
    const r = await client.query(`DELETE FROM menu_info WHERE objid = ANY($1::bigint[])`, [ids]);
    await client.query("COMMIT");
    return NextResponse.json({ success: true, deleted: r.rowCount, ids });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Menu delete:", e);
    const msg = e instanceof Error ? e.message : "삭제 중 오류";
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  } finally {
    client.release();
  }
}
