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

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)
    {
        var registrations = await _registrationService.GetByTournamentEventLevelAsync(tournamentEventLevelId);
        ViewBag.TournamentEventLevelId = tournamentEventLevelId;
        return View(registrations);
    }

    [HttpPost]
    public async Task<IActionResult> RecordScore([FromBody] ScoreCreateDto dto)
    {
        var recordedBy = User.Identity?.Name ?? "Unknown";
        var score = await _scoringService.RecordScoreAsync(dto, recordedBy);
        return Json(new { success = true, score });
    }

    [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 });
    }
}
