using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SportsDivision.Application.DTOs;
using SportsDivision.Application.Interfaces;
using SportsDivision.Domain.Enums;

namespace SportsDivision.Web.Controllers;

[Authorize]
public class FieldEventController : Controller
{
    private readonly IScoringService _scoringService;
    private readonly IRegistrationService _registrationService;
    private readonly ITournamentService _tournamentService;

    public FieldEventController(
        IScoringService scoringService,
        IRegistrationService registrationService,
        ITournamentService tournamentService)
    {
        _scoringService = scoringService;
        _registrationService = registrationService;
        _tournamentService = tournamentService;
    }

    [HttpGet]
    public async Task<IActionResult> Index(int tournamentEventLevelId)
    {
        if (tournamentEventLevelId <= 0)
        {
            ViewBag.ScoringTargets = await _tournamentService.GetEventLevelsByCategoryAsync(EventCategory.Field);
            ViewBag.ScoringController = "FieldEvent";
            ViewBag.ScoringTitle = "Field Event Scoring";
            return View("SelectEventLevel");
        }
        var registrations = await _registrationService.GetByTournamentEventLevelAsync(tournamentEventLevelId);
        ViewBag.TournamentEventLevelId = tournamentEventLevelId;
        return View(registrations);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> RecordScore(ScoreCreateDto dto, int tournamentEventLevelId)
    {
        var recordedBy = User.Identity?.Name ?? "Unknown";
        await _scoringService.RecordScoreAsync(dto, recordedBy);
        TempData["SuccessMessage"] = "Performance recorded.";
        return RedirectToAction(nameof(Index), new { tournamentEventLevelId });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CalculateScores(int tournamentEventLevelId)
    {
        var recordedBy = User.Identity?.Name ?? "Unknown";
        await _scoringService.CalculateFinalScoresAsync(tournamentEventLevelId, recordedBy);
        return RedirectToAction(nameof(Index), new { tournamentEventLevelId });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CalculatePlacements(int tournamentEventLevelId)
    {
        await _scoringService.CalculatePlacementsAsync(tournamentEventLevelId);
        return RedirectToAction(nameof(Index), new { tournamentEventLevelId });
    }
}
