using e_suite.API.Common.models;
using e_suite.API.Common.repository;
using e_suite.Database.Core;
using e_suite.Database.Core.Tables.Diagnostics;
using eSuite.Core.Clock;

namespace e_suite.Modules.PerformanceManager.repository;

public class PerformanceManagerRepository: RepositoryBase, IPerformanceManagerRepository
{
    private readonly IClock _clock;

    public PerformanceManagerRepository(IEsuiteDatabaseDbContext databaseDbContext, IClock clock) : base(databaseDbContext)
    {
        _clock = clock;
    }
    
    public IQueryable<PerformanceReportSummary> GetPerformanceReportSummary()
    {
        var now = _clock.GetNow;

        return DatabaseDbContext.PerformanceReports
            .Where( x => x.StartDateTime > now.AddYears(-1))
            .GroupBy( x => new{ x.Host, x.ControllerName, x.ActionName, x.RequestType} )
            .Select(r => new PerformanceReportSummary
            {
                Host = r.Key.Host,
                ControllerName = r.Key.ControllerName,
                ActionName = r.Key.ActionName,
                RequestType = r.Key.RequestType,
                MinTotalTimeMs = r.ToArray().Min( x => x.TotalTimeMS),
                MaxTotalTimeMs = r.ToArray().Max(x => x.TotalTimeMS),
                AvgTotalTimeMs = r.ToArray().Average(x => x.TotalTimeMS),
                SumTotalTimeMs = r.ToArray().Sum(x => x.TotalTimeMS),
                Count = r.Count()
            });
    }

    public IQueryable<PerformanceReport> GetPerformanceReports(string hostName, string controllerName, string actionName, string requestType)
    {
        return DatabaseDbContext.PerformanceReports
            .Where( x => x.Host == hostName && x.ControllerName == controllerName && x.ActionName == actionName && x.RequestType == requestType);
    }
}
