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

// 사용자(작업자) 목록 (user_info) - 드롭다운용
// body.dept_code로 부서 필터 가능
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const conditions: string[] = ["COALESCE(U.status, 'active') = 'active'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.dept_code) {
    conditions.push(`U.dept_code = $${idx++}`);
    params.push(body.dept_code);
  }

  const where = conditions.join(" AND ");
  const rows = await queryRows(
    `SELECT U.user_id AS "USER_ID",
       U.user_name AS "USER_NAME",
       U.dept_code AS "DEPT_CODE",
       U.dept_name AS "DEPT_NAME"
     FROM user_info U
     WHERE ${where}
     ORDER BY U.dept_name NULLS LAST, U.user_name
`,
    params,
  );
  return NextResponse.json({ RESULTLIST: rows });
}
