using Managing.Application.Abstractions.Services;
using Managing.Application.ManageBot.Commands;
using Managing.Domain.Statistics;
using MediatR;

namespace Managing.Application.ManageBot
{
    /// <summary>
    /// Handler for retrieving all agent summaries with complete data
    /// </summary>
    public class GetAllAgentSummariesCommandHandler : IRequestHandler<GetAllAgentSummariesCommand,
        IEnumerable<AgentSummary>>
    {
        private readonly IAgentService _agentService;

        public GetAllAgentSummariesCommandHandler(IAgentService agentService)
        {
            _agentService = agentService;
        }

        public async Task<IEnumerable<AgentSummary>> Handle(GetAllAgentSummariesCommand request,
            CancellationToken cancellationToken)
        {
            // Get all agent summaries from the database
            var allAgentSummaries = await _agentService.GetAllAgentSummaries();

            if (request.TimeFilter != "Total")
            {
                var cutoffDate = GetCutoffDate(request.TimeFilter);
                allAgentSummaries = allAgentSummaries.Where(a =>
                    a.UpdatedAt >= cutoffDate ||
                    (a.Runtime.HasValue && a.Runtime.Value >= cutoffDate));
            }

            return allAgentSummaries;
        }

        /// <summary>
        /// Gets the cutoff date based on the time filter
        /// </summary>
        private DateTime GetCutoffDate(string timeFilter)
        {
            return timeFilter switch
            {
                "24H" => DateTime.UtcNow.AddHours(-24),
                "3D" => DateTime.UtcNow.AddDays(-3),
                "1W" => DateTime.UtcNow.AddDays(-7),
                "1M" => DateTime.UtcNow.AddMonths(-1),
                "1Y" => DateTime.UtcNow.AddYears(-1),
                _ => DateTime.MinValue // Default to include all data
            };
        }
    }
}