using EonaCat.Logger.Server.Data;
using EonaCat.Logger.Server.Services;
using Microsoft.EntityFrameworkCore;

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

public class AnalyticsResult
{
    public int TotalEvents { get; set; }
    public List<EventSummary> TopEvents { get; set; } = new();
    public Dictionary<string, int> EventsByApplication { get; set; } = new();
    public Dictionary<string, int> EventsByHour { get; set; } = new();
    public List<UserActivity> TopUsers { get; set; } = new();
}

public class EventSummary
{
    public string Event { get; set; } = string.Empty;
    public int Count { get; set; }
    public string? LastSeen { get; set; }
}

public class UserActivity
{
    public string UserId { get; set; } = string.Empty;
    public int EventCount { get; set; }
    public List<string> TopEvents { get; set; } = new();
}

public class AnalyticsService : IAnalyticsService
{
    private readonly LoggerDbContext _context;

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

    public async Task<AnalyticsResult> GetAnalyticsAsync(DateTime startDate, DateTime endDate)
    {
        var analyticsLogs = await _context.LogEntries
            .Where(l => l.Level == 7 && l.Timestamp >= startDate && l.Timestamp <= endDate)
            .ToListAsync();

        var topEvents = analyticsLogs
            .GroupBy(l => l.Message)
            .Select(g => new EventSummary
            {
                Event = g.Key,
                Count = g.Count(),
                LastSeen = g.Max(l => l.Timestamp).ToString("yyyy-MM-dd HH:mm:ss")
            })
            .OrderByDescending(e => e.Count)
            .Take(10)
            .ToList();

        var eventsByApp = analyticsLogs
            .GroupBy(l => l.ApplicationName)
            .ToDictionary(g => g.Key, g => g.Count());

        var eventsByHour = analyticsLogs
            .GroupBy(l => l.Timestamp.Hour)
            .ToDictionary(g => $"{g.Key:D2}:00", g => g.Count());

        var topUsers = analyticsLogs
            .Where(l => !string.IsNullOrEmpty(l.UserId))
            .GroupBy(l => l.UserId!)
            .Select(g => new UserActivity
            {
                UserId = g.Key,
                EventCount = g.Count(),
                TopEvents = g.GroupBy(l => l.Message)
                    .OrderByDescending(eg => eg.Count())
                    .Take(3)
                    .Select(eg => eg.Key)
                    .ToList()
            })
            .OrderByDescending(u => u.EventCount)
            .Take(10)
            .ToList();

        return new AnalyticsResult
        {
            TotalEvents = analyticsLogs.Count,
            TopEvents = topEvents,
            EventsByApplication = eventsByApp,
            EventsByHour = eventsByHour,
            TopUsers = topUsers
        };
    }
}