using LogCentral.Server.Data;
using LogCentral.Server.Services;
using Microsoft.EntityFrameworkCore;

public interface IAnalyticsService
{
    Task<Dictionary<string, object>> GetAnalyticsAsync(DateTime startDate, DateTime endDate);
}

public class AnalyticsService : IAnalyticsService
{
    private readonly LogCentralDbContext _context;

    public AnalyticsService(LogCentralDbContext context)
    {
        _context = context;
    }

    public async Task<Dictionary<string, object>> GetAnalyticsAsync(DateTime startDate, DateTime endDate)
    {
        var logs = await _context.LogEntries
            .Where(l => l.Timestamp >= startDate && l.Timestamp <= endDate)
            .ToListAsync();

        return new Dictionary<string, object>
        {
            ["totalEvents"] = logs.Count(l => l.Level == 7),
            ["topEvents"] = logs
                .Where(l => l.Level == 7)
                .GroupBy(l => l.Message)
                .Select(g => new { Event = g.Key, Count = g.Count() })
                .OrderByDescending(x => x.Count)
                .Take(10)
                .ToList()
        };
    }
}