/**
 * @file time_utils.cpp
 * @brief Time utility functions implementation
 * @author Mahmoud Elmohtady
 * @company Nabd solutions - ASF
 * @copyright Copyright (c) 2025
 */

#include "time_utils.hpp"
#include <ctime>
#include <sys/time.h>
#include <cstdio>

namespace asf {
namespace utils {

bool setSystemTime(const std::string& isoTimeStr) {
    struct tm tm_time = {0};
    int ms = 0;

    // Parse ISO 8601: 2025-01-01T00:00:00.423Z
    if (sscanf(isoTimeStr.c_str(), "%d-%d-%dT%d:%d:%d.%dZ",
               &tm_time.tm_year, &tm_time.tm_mon, &tm_time.tm_mday,
               &tm_time.tm_hour, &tm_time.tm_min, &tm_time.tm_sec, &ms) < 6) {
        return false;
    }

    tm_time.tm_year -= 1900;
    tm_time.tm_mon -= 1;

    time_t t = mktime(&tm_time);
    if (t == -1) {
        return false;
    }

    struct timeval tv;
    tv.tv_sec = t;
    tv.tv_usec = ms * 1000;

    return settimeofday(&tv, nullptr) == 0;
}

} // namespace utils
} // namespace asf
