#pragma once

#include <string>
#include <vector>
#include <map>
#include <mutex>
#include <atomic>
#include "http_validator.h"

struct lua_State;

namespace mosis {

struct HttpRequest {
    std::string url;
    std::string method = "GET";
    std::map<std::string, std::string> headers;
    std::string body;
    int timeout_ms = 30000;
};

struct HttpResponse {
    int status_code = 0;
    std::map<std::string, std::string> headers;
    std::string body;
    std::string error;
};

struct NetworkLimits {
    size_t max_request_body = 10 * 1024 * 1024;     // 10 MB
    size_t max_response_body = 50 * 1024 * 1024;    // 50 MB
    int max_timeout_ms = 60000;                      // 60 seconds
    int max_concurrent_requests = 6;
    int default_timeout_ms = 30000;
};

class NetworkManager {
public:
    NetworkManager(const std::string& app_id, const NetworkLimits& limits = NetworkLimits{});
    ~NetworkManager();

    // Configure domain restrictions
    void SetAllowedDomains(const std::vector<std::string>& domains);
    void ClearDomainRestrictions();

    // Synchronous request
    // In test mode, validates but doesn't actually make network calls
    HttpResponse Request(const HttpRequest& request, std::string& error);

    // Stats
    int GetActiveRequestCount() const;

    // Access validator for testing
    HttpValidator& GetValidator() { return m_validator; }
    const HttpValidator& GetValidator() const { return m_validator; }

    // For testing: set mock mode (no actual network calls)
    void SetMockMode(bool enabled) { m_mock_mode = enabled; }
    bool IsMockMode() const { return m_mock_mode; }

private:
    std::string m_app_id;
    NetworkLimits m_limits;
    HttpValidator m_validator;
    std::atomic<int> m_active_requests{0};
    std::mutex m_mutex;
    bool m_mock_mode = true;  // Default to mock mode for tests

    // Validate request before sending
    bool ValidateRequest(const HttpRequest& request, std::string& error);
};

// Register network.* APIs as globals
void RegisterNetworkAPI(lua_State* L, NetworkManager* manager);

} // namespace mosis
