using Infrastructure.CloudSdk.mqttmessagecenter;
using OpenAuth.App.ServiceApp;
using OpenAuth.Repository.Domain;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace OpenAuth.WebApi.Model.mqtt
{
    public class ThingStatusHandler : IMqttMessageHandler
    {
        private readonly ILogger<ThingStatusHandler> _logger;
        AirportMaintenanceApp _app;
        private readonly MqttClientManager _mqttClientManager;
        public ThingStatusHandler(ILogger<ThingStatusHandler> logger, AirportMaintenanceApp app, MqttClientManager mqttClientManager)
        {
            _logger = logger;
            _app = app;
            _mqttClientManager = mqttClientManager;
        }

        public bool CanHandle(string topic)
        {
            return topic.Contains("/status");
        }

        public async Task HandleAsync(string topic, string payload)
        {
            _logger.LogError($"[Service] Topic={topic}, Payload={payload}");
            Console.WriteLine($"[Service] Topic={topic}, Payload={payload}");

            if (payload.Contains("update_topo"))
            {
                var root = JsonNode.Parse(payload)?.AsObject();
                if (root == null)
                {
                    return;
                }
                var bid = root["bid"]?.ToString() ?? "";
                var tid = root["tid"]?.ToString() ?? "";
                var timestamp = long.Parse(root["timestamp"]?.ToString() ?? "0");
                var requestData = new
                {
                    bid = bid,
                    method = "update_topo",
                    tid = tid,
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    data = new
                    {
                        result = 0,
                    }
                };
                string getway = topic.Split('/')[2];
                string payloadreq = JsonSerializer.Serialize(requestData);
                await _mqttClientManager.PublishAsync($"sys/product/{getway}/status_reply", payloadreq);
            }
        }
    }
}
