import { NextRequest, NextResponse } from "next/server";
import { queryRows } 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 conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.user_name) {
    conditions.push(`U.user_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.user_name);
  }
  if (body.dept_name) {
    conditions.push(`U.dept_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.dept_name);
  }
  if (body.user_type) {
    conditions.push(`U.user_type = $${idx++}`);
    params.push(body.user_type);
  }
  if (body.status) {
    conditions.push(`COALESCE(U.status, 'active') = $${idx++}`);
    params.push(body.status);
  }

  const where = conditions.join(" AND ");

  const sql = `
    SELECT U.user_id AS "USER_ID", U.user_name AS "USER_NAME", U.dept_name AS "DEPT_NAME",
      U.sabun AS "SABUN", U.position_name AS "POSITION_NAME", U.email AS "EMAIL",
      U.cell_phone AS "CELL_PHONE", U.tel AS "TEL", U.user_type_name AS "USER_TYPE_NAME",
      U.user_type AS "USER_TYPE",
      TO_CHAR(U.regdate, 'YYYY-MM-DD') AS "REGDATE",
      COALESCE(U.status, 'active') AS "STATUS",
      COALESCE(U.unlimited_qty, 'N') AS "UNLIMITED_QTY",
      COALESCE(U.view_hidden, 'N')   AS "VIEW_HIDDEN",
      COALESCE((SELECT STRING_AGG(AM.auth_name, ',') FROM authority_sub_user ASU JOIN authority_master AM ON AM.objid = ASU.master_objid WHERE ASU.user_id = U.user_id), '') AS "AUTH_NAME"
    FROM user_info U
    WHERE ${where}
    ORDER BY U.dept_name, U.user_name
  `;

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