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

// 권한그룹에 미소속 사용자 조회 (getAuthNotInUserList 대응)
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 conditions: string[] = ["UI.USER_ID IS NOT NULL"];
    const params: unknown[] = [];
    let idx = 1;

    if (body.userName) {
      conditions.push(`UI.USER_NAME LIKE '%' || $${idx++} || '%'`);
      params.push(body.userName);
    }
    if (body.deptName) {
      conditions.push(`UI.DEPT_NAME LIKE '%' || $${idx++} || '%'`);
      params.push(body.deptName);
    }
    if (body.masterObjid) {
      conditions.push(`NOT EXISTS (SELECT 1 FROM AUTHORITY_SUB_USER ASU WHERE ASU.USER_ID = UI.USER_ID AND ASU.MASTER_OBJID = $${idx++}::numeric)`);
      params.push(body.masterObjid);
    }

    const rows = await queryRows(
      `SELECT UI.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"
       FROM USER_INFO UI
       WHERE ${conditions.join(" AND ")}
       ORDER BY UI.DEPT_NAME, UI.USER_NAME
`,
      params
    );

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