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

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

  const sql = `
    SELECT TO_CHAR(F.log_time, 'YYYY-MM-DD HH24:MI:SS') AS "LOG_TIME",
      COALESCE((SELECT user_name FROM user_info WHERE user_id = F.user_id LIMIT 1), F.user_id) AS "USER_NAME",
      COALESCE(AFI.real_file_name, '') AS "REAL_FILE_NAME", COALESCE(AFI.doc_type_name, '') AS "DOC_TYPE_NAME",
      F.remote_addr AS "REMOTE_ADDR"
    FROM file_down_log F
    LEFT JOIN attach_file_info AFI ON AFI.objid = F.file_objid
    WHERE ${where}
    ORDER BY F.log_time DESC
  `;

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