using CMSMicroservice.Protobuf.Protos.Health;
using CMSMicroservice.Application.HealthCQ.Queries.GetSystemHealth;
using MediatR;
using Mapster;
using Grpc.Core;
using Google.Protobuf.WellKnownTypes;
using System.Linq;

namespace CMSMicroservice.WebApi.Services;

public class HealthService : HealthContract.HealthContractBase
{
    private readonly IMediator _mediator;

    public HealthService(IMediator mediator)
    {
        _mediator = mediator;
    }

    public override async Task<GetSystemHealthResponse> GetSystemHealth(Empty request, ServerCallContext context)
    {
        var query = new GetSystemHealthQuery();
        var result = await _mediator.Send(query, context.CancellationToken);
        
        return result.Adapt<GetSystemHealthResponse>();
    }

    #region [ARCHIVED] GetServiceHealth — تکراری: GetSystemHealth کل سیستم را برمی‌گرداند، فیلتر client-side کافی است
    [Obsolete("ARCHIVED: Use GetSystemHealth + client-side filter by service name")]
    public override async Task<GetServiceHealthResponse> GetServiceHealth(GetServiceHealthRequest request, ServerCallContext context)
    {
        // [ARCHIVED] duplicate — GetSystemHealth returns all, client can filter
        var systemHealthQuery = new GetSystemHealthQuery();
        var systemHealth = await _mediator.Send(systemHealthQuery, context.CancellationToken);
        
        var service = systemHealth.Services.FirstOrDefault(s => 
            s.ServiceName.Equals(request.ServiceName, StringComparison.OrdinalIgnoreCase));

        if (service == null)
        {
            throw new ArgumentException($"Service '{request.ServiceName}' not found");
        }

        return new GetServiceHealthResponse
        {
            Service = service.Adapt<ServiceHealthModel>(),
            CheckedAt = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow)
        };
    }
    #endregion
}