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_id) {
    conditions.push(`L.user_id LIKE '%' || $${idx++} || '%'`);
    params.push(body.user_id);
  }
  if (body.login_result) {
    conditions.push(`L.login_result = $${idx++}`);
    params.push(body.login_result);
  }
  if (body.start_date) {
    conditions.push(`L.log_time >= $${idx++}::timestamp`);
    params.push(body.start_date);
  }
  if (body.end_date) {
    conditions.push(`L.log_time <= ($${idx++} || ' 23:59:59')::timestamp`);
    params.push(body.end_date);
  }

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

  const sql = `
    SELECT TO_CHAR(L.log_time, 'YYYY-MM-DD HH24:MI:SS') AS "LOG_TIME",
      L.user_id AS "USER_ID", L.login_result AS "LOGIN_RESULT",
      L.remote_addr AS "REMOTE_ADDR", L.error_message AS "ERROR_MESSAGE"
    FROM login_access_log L
    WHERE ${where}
    ORDER BY L.log_time DESC
  `;

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