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

// 환율관리 (admin/getExchangeRateMngList.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.yyyy_mm) {
    conditions.push(`E.yyyy_mm LIKE '%' || $${idx++} || '%'`);
    params.push(body.yyyy_mm);
  }
  if (body.from_date) {
    conditions.push(`E.yyyy_mm >= $${idx++}`);
    params.push(body.from_date);
  }
  if (body.to_date) {
    conditions.push(`E.yyyy_mm <= $${idx++}`);
    params.push(body.to_date);
  }

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

  const sql = `
    SELECT E.yyyy_mm AS "YYYY_MM",
      E.yyyy_mm_dd AS "YYYY_MM_DD",
      E.cost_usd AS "COST_USD",
      E.cost_eu AS "COST_EU",
      E.cost_japan AS "COST_JAPAN",
      E.cost_china AS "COST_CHINA",
      E.cost_vietnam AS "COST_VIETNAM",
      E.cost_rub AS "COST_RUB",
      E.cost_inr AS "COST_INR",
      E.cost_thb AS "COST_THB",
      E.cost_hkd AS "COST_HKD",
      E.writer AS "WRITER",
      TO_CHAR(E.regdate, 'YYYY-MM-DD') AS "REGDATE",
      TO_CHAR(E.api_date, 'YYYY-MM-DD HH24:MI') AS "API_DATE"
    FROM comm_exchange_rate E
    WHERE ${where}
    ORDER BY E.yyyy_mm DESC, E.yyyy_mm_dd 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 });
  }
}
