using IWS5.Api.Enum;
using IWS5.Api.OptionsSetup;
using IWS5.Core.DTO;
using IWS5.Core.Enums;
using IWS5.Core.Models;
using IWS5.Core.Models.Request;
using IWS5.Core.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;

namespace IWS5.Api.Controllers;

[Authorize(Roles = nameof(UserGroups.PDAdminGroup))]
[Route("api/[controller]")]
[ApiController]
public class ConnectionController(IConnectionService connectionService, ILogger<ConnectionController> logger) : ControllerBase
{
    /// <summary>
    /// Gets a list of connections based on the connection type.
    /// </summary>
    /// <param name="connectionType">The type of connection to filter by.</param>
    /// <returns>A list of connections.</returns>
    /// <response code="200">Returns the list of connections</response>
    /// <response code="401">If the token is invalid or missing</response>
    /// [SwaggerOperation(Summary = "Gets a list of connections", Description = "Gets a list of connections based on the connection type.")]
    [SwaggerResponse(200, "Returns the list of connections", typeof(Response<ConnectionListItemDTO[]>))]
    [SwaggerResponse(401, "If the token is invalid or missing")]
    [HttpGet("list")]
    public async Task<IActionResult> GetConnections([FromQuery] ATConnectionType connectionType)
    {
        string userName;
        try
        {
            userName = JwtTokenHelper.GetUserEmailFromToken(HttpContext);
            logger.LogInformation("Fetching connections for user {UserName}", userName);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Error retrieving user email from token");
            // If there's an issue with the token, return Unauthorized (401).
            return Unauthorized(new { message = "Invalid or missing token", error = ex.Message });
        }

        var result = await connectionService.ListConnections(new ListConnectionRequest(userName, connectionType));
        logger.LogInformation("Successfully fetched {connections} connections for user {UserName}", result, userName);

        return Ok(result);
    }
}
