#include "ResourceManager.h"
#include <future>

namespace resources {

ResourceManager::ResourceManager() = default;
ResourceManager::~ResourceManager() = default;

std::future<std::shared_ptr<void>> ResourceManager::loadAsync(const std::string& key, std::function<std::shared_ptr<void>(const std::string&)> loader)
{
    // Quick check for existing cached resource
    {
        std::lock_guard<std::mutex> lk(mutex_);
        auto it = cache_.find(key);
        if (it != cache_.end()) {
            // Return already-available resource (keep strong ref)
            auto sp = it->second;
            if (sp) {
                return std::async(std::launch::deferred, [sp]() { return sp; });
            }
        }
    }

    // Launch async loader
    return std::async(std::launch::async, [this, key, loader]() {
        auto res = loader(key);
        if (res) {
            std::lock_guard<std::mutex> lk(mutex_);
            cache_[key] = res; // store strong reference
        }
        return res;
    });
}

void ResourceManager::put(const std::string& key, std::shared_ptr<void> resource)
{
    std::lock_guard<std::mutex> lk(mutex_);
    cache_[key] = resource; // store strong reference so callers using raw pointers stay valid
}

} // namespace resources
