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

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

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

        public Task HandleAsync(string topic, string payload)
        {
            _logger.LogError($"[Service] Topic={topic}, Payload={payload}");
            Console.WriteLine($"[Service] Topic={topic}, Payload={payload}");
            var root = JsonNode.Parse(payload)?.AsObject();
            _app.AddLog(new LasaLog
            {
                Id = Guid.NewGuid().ToString(),
                Topic = topic,
                Method = root["method"]?.ToString() ?? "",
                CreateTime = DateTime.Now,
                Data = root
            });
            return Task.CompletedTask;
        }
    }
}
