using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SportsDivision.Application.Interfaces;

namespace SportsDivision.Web.Controllers;

[Authorize]
public class DashboardController : Controller
{
    private readonly IDashboardService _dashboardService;
    private readonly ITournamentService _tournamentService;

    public DashboardController(IDashboardService dashboardService, ITournamentService tournamentService)
    {
        _dashboardService = dashboardService;
        _tournamentService = tournamentService;
    }

    public async Task<IActionResult> Index(int? tournamentId)
    {
        // "Active" tournaments are the non-archived ones; archived tournaments are never shown here.
        var tournaments = (await _tournamentService.GetAllAsync(includeArchived: false)).ToList();

        // Ignore a selection that points at an archived/unknown tournament.
        int? selectedId = tournamentId.HasValue && tournaments.Any(t => t.TournamentId == tournamentId.Value)
            ? tournamentId
            : null;

        // With exactly one active tournament, show it automatically — no need to choose.
        // With several, the user must pick one (selectedId stays null until they do).
        if (!selectedId.HasValue && tournaments.Count == 1)
        {
            selectedId = tournaments[0].TournamentId;
        }

        var dashboard = await _dashboardService.GetDashboardAsync(selectedId);

        ViewBag.Tournaments = tournaments;
        ViewBag.SelectedTournamentId = selectedId;

        return View(dashboard);
    }
}
