import { Request, Response } from "express";
import * as env from "../config/env.config";
import * as loggers from "../common/logger";
import axios from "axios";
import RateHistory from "../models/rateHistory";
import { startOfToday, startOfTomorrow, tryCatch } from "../common/helper";
import { getRateS } from "../services/rateService";

export const getRate = async (req: Request, res: Response) => {
  // const todayStart = startOfToday();
  // const tomorrowStart = startOfTomorrow();

  // const rate = await RateHistory.findOne({
  //   validDate: {
  //     $gte: todayStart, // Greater than or equal to the start of today
  //     $lt: tomorrowStart, // Less than the start of tomorrow
  //   },
  // });

  // if (rate) {
  //   console.log("rate found", rate);
  //   return res.status(200).send({ success: true, data: rate });
  // } else {
  //   const { data, error } = await tryCatch(axios.post("https://tasa.legendsoft.com/api/tasa/get"));
  //   if (error) {
  //     loggers.error(error.message);
  //     res.status(500).send({ success: false, message: "Error getting rate" });
  //   }

  //   if (data) {
  //     const exists = await RateHistory.findOne({ validDate: data!.data.FechaValor });
  //     if (!exists) {
  //       const rateHistory = new RateHistory({
  //         date: data!.data.Fecha,
  //         validDate: data!.data.FechaValor,
  //         usd: data!.data.USD,
  //         rub: data!.data.RUB,
  //         try: data!.data.TRY,
  //         cny: data!.data.CNY,
  //         eur: data!.data.EUR,
  //       });
  //       await rateHistory.save();
  //       return res.status(200).send({ success: true, data: rateHistory });
  //     } else {
  //       return res.status(200).send({ success: true, data: exists });
  //     }
  //   }
  //   res.status(500).send({ success: false, message: "Error getting rate" });
  // }

  const rate = await getRateS();
  if (!rate) {
    return res
      .status(500)
      .send({ success: false, message: "Error getting rate" });
  }

  return res.status(200).send({ success: true, data: rate });
};

export const getRateHistories = async (req: Request, res: Response) => {
  const page = parseInt(req.query.page as string) || 1; // Default to page 1 if not provided
  const limit = parseInt(req.query.limit as string) || 10; // Default to 10 items per page if not provided
  const globalFilter = req.query.globalFilter as string;
  const skip = (page - 1) * limit;

  // const filter: any = {
  //   status: "active",
  // };
  // if (globalFilter) {
  //   // Create a case-insensitive regular expression for the search term
  //   const regex = new RegExp(globalFilter, "i");

  //   // Use the $or operator to search across multiple fields
  //   filter.$or = [
  //     { name: { $regex: regex } },
  //     { rif: { $regex: regex } },
  //     { email: { $regex: regex } },
  //   ];
  // }

  const totalCount = await RateHistory.countDocuments();

  const rateHistories = await RateHistory.find()
    .select("createdAt validDate usd")
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(limit)
    .lean()
    .exec();

  return res.status(200).json({
    success: true,
    message: "Tasas obtenidas",
    data: rateHistories,
    totalCount: totalCount,
  });
};
