using System.Text.Json;
using BrikInstaller;

public static class NetworkService {
    public static async Task<object> HandleFetchRequest(JsonElement jsonPayload) {
        try {
            string url = jsonPayload.GetProperty("url").GetString()!;
            string httpMethodStr = jsonPayload.TryGetProperty("method", out var m) ? m.GetString()! : "GET";
            string? body = jsonPayload.TryGetProperty("body", out var b) ? b.GetString() : null;
            
            Dictionary<string, string>? headers = null;
            if (jsonPayload.TryGetProperty("headers", out var h)) {
                headers = JsonSerializer.Deserialize<Dictionary<string, string>>(h.GetRawText(), Constants._jsonOptions);
            }

            var httpMethod = new HttpMethod(httpMethodStr.ToUpper());
            var response = await HttpHelper.FetchAsync(url, httpMethod, body, headers);
            
            string content = await response.Content.ReadAsStringAsync();
            
            return new {
                status = (int)response.StatusCode,
                success = response.IsSuccessStatusCode,
                data = content
            };
        } catch (Exception ex) {
            return new { success = false, error = ex.Message };
        }
    }
}