#pragma once
#include <cstdint>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

#include "Web/MapRegistry.h"

// -------------------------------------------------------------------------
// MapTileService
// Loads a full map PNG on first request, caches it in memory, and serves
// 512×512 tiles on demand (nearest-neighbour resampled).
// -------------------------------------------------------------------------

class MapTileService {
public:
    /// Return PNG-encoded bytes for the requested tile.
    /// errCode is set to one of: 200, 400, 404, 500.
    /// An empty vector is returned for any non-200 result.
    std::vector<uint8_t> GetTile(const MapInfo& map, int tileX, int tileY,
                                 int& errCode);

private:
    struct Image {
        std::vector<uint8_t> pixels; // RGBA, row-major
        int w = 0;
        int h = 0;
    };

    std::mutex                              m_mutex;
    std::unordered_map<std::string, Image>  m_cache; // mapId → loaded image

    /// Return cached Image or attempt to load it.  Returns nullptr on failure.
    const Image* LoadOrGet(const std::string& mapId);
};
