using Hc900.Gateway;
using Microsoft.Extensions.Logging;

namespace Hc900Crawler.Infrastructure.Hc900;

public class Hc900WriteService
{
    private readonly ControllerGrpcClientPool _clientPool;
    private readonly ILogger<Hc900WriteService> _logger;

    public Hc900WriteService(ControllerGrpcClientPool clientPool, ILogger<Hc900WriteService> logger)
    {
        _clientPool = clientPool;
        _logger = logger;
    }

    public async Task<(bool Success, string Error)> WriteTagAsync(string controllerId, string tagName, double value)
    {
        try
        {
            var client = _clientPool.GetClient(controllerId);
            var resp = await client.WriteTagAsync(new WriteTagRequest { TagName = tagName, Value = value });
            if (!resp.Success)
                _logger.LogWarning("[Hc900Write] [{Id}] {Tag} = {Value} 실패: {Error}", controllerId, tagName, value, resp.Error);
            else
                _logger.LogInformation("[Hc900Write] [{Id}] {Tag} = {Value} 성공", controllerId, tagName, value);
            return (resp.Success, resp.Error ?? "");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[Hc900Write] [{Id}] {Tag} 쓰기 예외", controllerId, tagName);
            return (false, ex.Message);
        }
    }
}
