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

// 메일발송 로그 (admin/log/mailSendLogList.do 대응)
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.send_user_id) {
    conditions.push(`M.send_user_id LIKE '%' || $${idx++} || '%'`);
    params.push(body.send_user_id);
  }
  if (body.receiver_to) {
    conditions.push(`M.receiver_to LIKE '%' || $${idx++} || '%'`);
    params.push(body.receiver_to);
  }
  if (body.title) {
    conditions.push(`M.title LIKE '%' || $${idx++} || '%'`);
    params.push(body.title);
  }
  if (body.mail_type) {
    conditions.push(`M.mail_type = $${idx++}`);
    params.push(body.mail_type);
  }
  if (body.is_send) {
    conditions.push(`M.is_send = $${idx++}`);
    params.push(body.is_send);
  }

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

  const sql = `
    SELECT M.objid AS "OBJID",
      M.system_name AS "SYSTEM_NAME",
      M.send_user_id AS "SEND_USER_ID",
      M.from_addr AS "FROM_ADDR",
      M.reception_user_id AS "RECEPTION_USER_ID",
      M.receiver_to AS "RECEIVER_TO",
      M.title AS "TITLE",
      M.mail_type AS "MAIL_TYPE",
      M.is_send AS "IS_SEND",
      TO_CHAR(M.log_time, 'YYYY-MM-DD HH24:MI:SS') AS "LOG_TIME",
      M.error_log AS "ERROR_LOG"
    FROM mail_log M
    WHERE ${where}
    ORDER BY M.log_time DESC NULLS LAST
  `;

  try {
    const rows = await queryRows(sql, params);
    return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
  } catch (error) {
    console.error("메일발송 로그 조회 오류:", error);
    return NextResponse.json({ success: false, message: "처리 중 오류가 발생했습니다." }, { status: 500 });
  }
}
