using SportsDivision.Application.DTOs;
using SportsDivision.Application.Interfaces;
using SportsDivision.Domain.Enums;
using SportsDivision.Domain.Interfaces;

namespace SportsDivision.Application.Services;

public class DashboardService : IDashboardService
{
    private readonly IUnitOfWork _uow;
    private readonly IScoringService _scoringService;

    public DashboardService(IUnitOfWork uow, IScoringService scoringService)
    {
        _uow = uow;
        _scoringService = scoringService;
    }

    public async Task<DashboardDto> GetDashboardAsync(int? tournamentId = null)
    {
        var dashboard = new DashboardDto
        {
            TotalStudents = await _uow.Students.CountAsync(),
            MaleStudents = await _uow.Students.CountAsync(s => s.Sex == Sex.Male),
            FemaleStudents = await _uow.Students.CountAsync(s => s.Sex == Sex.Female),
            TotalSchools = await _uow.Schools.CountAsync(),
            ActiveTournaments = await _uow.Tournaments.CountAsync(t => t.Status == TournamentStatus.InProgress && !t.IsArchived)
        };

        if (tournamentId.HasValue)
        {
            var tels = await _uow.TournamentEventLevels.GetByTournamentAsync(tournamentId.Value);
            int regCount = 0;
            foreach (var tel in tels)
            {
                var regs = await _uow.EventRegistrations.GetByTournamentEventLevelAsync(tel.TournamentEventLevelId);
                regCount += regs.Count();
            }
            dashboard.TotalRegistrations = regCount;

            var standings = await _scoringService.GetSchoolStandingsAsync(tournamentId.Value);
            dashboard.TopSchools = standings.Take(10).ToList();
        }

        return dashboard;
    }
}
