using IWS5.Api.Helpers;
using IWS5.Api.OptionsSetup;
using IWS5.Core.DTO;
using IWS5.Core.Exceptions;
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;

/// <summary>
/// Controller for managing queues.
/// </summary>
/// <param name="queueService">Service for handling queue-related operations.</param>
/// <param name="logger">Logger for logging information and errors.</param>
[Authorize]
[Route("api/[controller]")]
[ApiController]
[SwaggerTag("Controller for managing queues.")]
public class QueueController(IQueueService queueService, ILogger<QueueController> logger)
    : ControllerBase
{
    /// <summary>
    /// Retrieves a list of queues for a specific process.
    /// </summary>
    /// <param name="processId">The ID of the process.</param>
    /// <returns>A list of queues.</returns>
    /// <response code="200">Returns the list of queues.</response>
    /// <response code="401">If the user is not authenticated.</response>
    /// <response code="500">If there is an internal server error.</response>
    [HttpGet("{processId:int}")]
    [SwaggerOperation(Summary = "Retrieves a list of queues for a specific process.")]
    [ProducesResponseType(typeof(Response<ListQueuesResponseDTO>), 200)]
    [ProducesResponseType(401)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetQueues([FromRoute] int processId)
    {
        var userName = JwtTokenHelper.GetUserName(HttpContext, logger, out var actionResult);

        if (string.IsNullOrEmpty(userName))
        {
            return actionResult;
        }

        try
        {
            logger.LogInformation("User {UserName} is attempting to retrieve queues for processId {processId}", userName, processId);
            // Call the service to get the list of queues
            var result = await queueService.ListQueues(new ListQueuesRequest(userName, processId));
            logger.LogInformation("Successfully retrieved {Queues} for user {UserName}", result, userName);
            var response = ResponseMapper<ListQueuesResponseDTO>.MapServiceResponse(result);
            return response;
        }
        catch (Exception ex)
        {
            // Log any errors that occur during queue retrieval
            logger.LogError(ex, "An error occurred while retrieving queues for user {UserName}", userName);
            return StatusCode(500, "An error occurred while retrieving queues.");
        }
    }
}
