using IWS5.Api.Helpers;
using IWS5.Api.OptionsSetup;
using IWS5.Core.DTO;
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 buttons.
/// </summary>
/// <param name="buttonService">Service for handling button-related operations.</param>
/// <param name="logger">Logger for logging information and errors.</param>
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ButtonsController(IButtonService buttonService, ILogger<ButtonsController> logger)
    : ControllerBase
{
    /// <summary>
    /// Retrieves a list of buttons for a specific queue.
    /// </summary>
    /// <param name="queueId">The ID of the queue to retrieve buttons for.</param>
    /// <param name="workItemReferenceId">Optional work item reference ID to retrieve buttons for an inbox.</param>
    /// <returns>A list of button items for the specified queue and optional work item.</returns>
    /// <response code="200">Returns the list of button items.</response>
    /// <response code="401">If the user is not authenticated.</response>
    /// <response code="404">If no matching event is found for the supplied queue ID.</response>
    /// <response code="500">If there is an internal server error.</response>
    [HttpGet]
    [SwaggerOperation(Summary = "Retrieves a list of buttons for a specific queue", 
        Description = "Gets buttons available for the authenticated user in the specified queue, optionally filtered by work item reference ID.")]
    [ProducesResponseType(typeof(List<ButtonListItemDTO>), 200)]
    [ProducesResponseType(401)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetButtonsList([FromQuery] int queueId, [FromQuery] int? workItemReferenceId = null)
    {
        var userName = JwtTokenHelper.GetUserName(HttpContext, logger, out var actionResult);

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

        try
        {
            var result = await buttonService.ListButtons(new ButtonRequest(userName, queueId, workItemReferenceId));
            var response = ResponseMapper<List<ButtonListItemDTO>>.MapServiceResponse(result);
            logger.LogInformation("Successfully retrieved buttons for user {UserName} from queue {QueueId}", userName, queueId);
            
            return response;
        }
        catch (Exception ex)
        {
            logger.LogError(ex,
                "An error occurred while retrieving buttons for user {UserName} from queue {QueueId}", userName,
                queueId);
            return StatusCode(500, new { message = "An error occurred while retrieving buttons.", error = ex.Message });
        }
    }
}