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

// 권한그룹 소속 멤버 조회 (selectAuthGroupMemberList 대응)
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 masterObjid = body.masterObjid;
    if (!masterObjid) return NextResponse.json({ RESULTLIST: [], TOTAL_CNT: 0 });

    const rows = await queryRows(
      `SELECT ASU.OBJID::text AS "OBJID",
              ASU.MASTER_OBJID::text AS "MASTER_OBJID",
              ASU.USER_ID AS "USER_ID",
              UI.USER_NAME AS "USER_NAME",
              UI.DEPT_NAME AS "DEPT_NAME",
              UI.USER_TYPE_NAME AS "USER_TYPE_NAME",
              UI.EMAIL AS "EMAIL",
              TO_CHAR(ASU.REGDATE, 'YYYY-MM-DD') AS "REGDATE"
       FROM AUTHORITY_SUB_USER ASU
       LEFT JOIN USER_INFO UI ON UI.USER_ID = ASU.USER_ID
       WHERE ASU.MASTER_OBJID = $1::numeric
       ORDER BY ASU.REGDATE DESC`,
      [masterObjid]
    );

    return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
  } catch (error) {
    console.error("Auth members:", error);
    return NextResponse.json({ success: false, message: "처리 중 오류가 발생했습니다." }, { status: 500 });
  }
}
