using System.Security.Claims;
using CalledIt.Domain.Dtos;
using CalledIt.Domain.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;

namespace CalledIt.Api.Controllers;

[ApiController]
[Authorize]
[Route("api/[controller]")]
public class LeaderboardController : ControllerBase
{
    private readonly ILeaderboardService _leaderboardService;

    public LeaderboardController(ILeaderboardService leaderboardService)
    {
        _leaderboardService = leaderboardService;
    }

    [HttpGet("{competitionId}")]
    [OutputCache(PolicyName = "Leaderboard")]
    [ProducesResponseType(typeof(LeaderboardResultDto), StatusCodes.Status200OK)]
    public async Task<ActionResult<LeaderboardResultDto>> GetByCompetition(int competitionId)
    {
        var result = await _leaderboardService.GetByCompetitionAsync(competitionId, GetCurrentUserId());
        return Ok(result);
    }

    private int GetCurrentUserId()
    {
        var claim = User.FindFirstValue("sub");
        if (claim is null || !int.TryParse(claim, out var id))
        {
            throw new UnauthorizedAccessException("Authenticated user identity is missing or invalid.");
        }
        return id;
    }
}
