using Azure.Core;
using IWS5.Api.Helpers;
using IWS5.Api.OptionsSetup;
using IWS5.Core.DTO;
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]
[Route("api/[controller]")]
[ApiController]
public class SignatureController(ISignatureService signatureService, ILogger<WorkItemController> logger)
: ControllerBase
{
    /// <summary>
    /// Sign list of workitems
    /// </summary>
    /// <param name="signRequest">The request containing the work item IDs to sign and certificate details.</param>
    /// <returns>The list of signed and skipped work items.</returns>
    [HttpPost("sign-workitem-list")]
    [SwaggerOperation(Summary = "Sign list of workitems.")]
    [ProducesResponseType(typeof(CodeResponse<SignatureResponseDTO>), 200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(401)]
    [ProducesResponseType(403)]
    [ProducesResponseType(409)]
    public async Task<IActionResult> SignWorkitems([FromBody]SignWorkitemListRequest signRequest)
    {
        var userName = JwtTokenHelper.GetUserName(HttpContext, logger, out var actionResult);

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

        try
        {
            var result = await signatureService.SignWorkItemList(signRequest, userName);
            var response = ResponseMapper<SignatureResponseDTO>.MapServiceResponse(result);
            return response;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An error occurred while signing list of workitems");
            return BadRequest("An error occurred while signing list of workitems.");
        }
    }
}