#include "biboumi.h"
#include <config/config.hpp>
#include <scheduler/scheduler.hpp>
#include <utils/parse_duration.hpp>
#include <utils/timed_events.hpp>

#ifdef USE_DATABASE
#include <database/database.hpp>
#endif

static const std::unordered_map<
    std::string, std::pair<std::chrono::seconds, std::function<void()>>>
    events = {
#ifdef USE_DATABASE
        {"cleanup_old_messages",
         {60s * 10 /* 10min */, &Scheduler::cleanup_old_messages}},
#endif
};

void Scheduler::start_scheduler() {
  for (const auto &job : events) {
    const std::string name = job.first;
    const std::chrono::seconds interval = job.second.first;
    const std::function<void()> job_function = job.second.second;
    // Run it once at startup
    job_function();
    // Then every interval
    TimedEventsManager::instance().add_event(
        TimedEvent(interval, job_function, name));
  }
}

void Scheduler::stop_scheduler() {
  for (const auto &job : events) {
    const std::string name = job.first;
    TimedEventsManager::instance().cancel(name);
  }
}

#ifdef USE_DATABASE
void Scheduler::cleanup_old_messages() {
  // Get the config value
  const std::string archive_expires_after =
      Config::get("archive_expires_after", "0");
  const std::optional<long> seconds =
      utils::parse_duration(archive_expires_after);
  // If it's actually set and relevant, start cleanup
  if (seconds.has_value() && seconds.value() != 0) {
    // Calculate age of messages to be deleted
    log_debug("[cleanup_old_messages] Deleting messages older than ",
              archive_expires_after, " (", seconds.value(), " seconds)");

    // Convert the config value to a duration
    const auto duration = std::chrono::duration<long>(seconds.value());
    // Get timestamp now relative to unix epoch
    const auto now = std::chrono::system_clock::now();
    // Older than this get deleted
    const auto ago = now - duration;
    // Convert to seconds since epoch
    const auto since_epoch = std::chrono::duration_cast<std::chrono::seconds>(
        ago.time_since_epoch());
    Database::delete_old_muclines(since_epoch.count());
  } else
    log_debug("[cleanup_old_messages] Not deleting anything. "
              "archive_expires_after is ",
              archive_expires_after);
}
#endif
