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

// 권한관리 목록 조회 (selectAuthMngList 대응)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const sql = `
    SELECT AM.objid::text AS "OBJID",
           AM.auth_name AS "AUTH_NAME",
           AM.auth_code AS "AUTH_CODE",
           COALESCE((SELECT COUNT(*)::int FROM authority_sub_user WHERE master_objid = AM.objid), 0) AS "USER_CNT",
           AM.writer AS "WRITER",
           TO_CHAR(AM.regdate, 'YYYY-MM-DD') AS "REGDATE",
           COALESCE(AM.status, 'active') AS "STATUS"
    FROM authority_master AM
    ORDER BY AM.regdate DESC
  `;

  const rows = await queryRows(sql);
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
