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

// common/getPageAuthInfo.do 대응 - 페이지 권한 조회
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) {
    return NextResponse.json({ success: false }, { status: 401 });
  }

  // 관리자는 모든 권한
  if (user.isAdmin) {
    return NextResponse.json({
      CREATE_AUTH_CNT: 1,
      READ_AUTH_CNT: 1,
      UPDATE_AUTH_CNT: 1,
      DELETE_AUTH_CNT: 1,
    });
  }

  const body = await request.json();
  const { menuObjId } = body;

  const result = await queryOne(
    `SELECT
       COALESCE(SUM(CASE WHEN RMA.AUTH_TYPE = 'CREATE' THEN 1 ELSE 0 END), 0) AS CREATE_AUTH_CNT,
       COALESCE(SUM(CASE WHEN RMA.AUTH_TYPE = 'READ' THEN 1 ELSE 0 END), 0) AS READ_AUTH_CNT,
       COALESCE(SUM(CASE WHEN RMA.AUTH_TYPE = 'UPDATE' THEN 1 ELSE 0 END), 0) AS UPDATE_AUTH_CNT,
       COALESCE(SUM(CASE WHEN RMA.AUTH_TYPE = 'DELETE' THEN 1 ELSE 0 END), 0) AS DELETE_AUTH_CNT
     FROM REL_MENU_AUTH RMA
     JOIN AUTHORITY_SUB_USER ASU ON RMA.AUTH_OBJID = ASU.MASTER_OBJID
     WHERE RMA.MENU_OBJID = $1 AND ASU.USER_ID = $2`,
    [menuObjId, user.userId]
  );

  return NextResponse.json(result || {
    CREATE_AUTH_CNT: 0,
    READ_AUTH_CNT: 0,
    UPDATE_AUTH_CNT: 0,
    DELETE_AUTH_CNT: 0,
  });
}
