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 tracking records.
/// </summary>
/// <param name="trackingRecordService">Service for handling tracking-related operations.</param>
/// <param name="logger">Logger for logging information and errors.</param>
[Authorize]
[Route("api/[controller]")]
[ApiController]
[SwaggerTag("Controller for managing tracking.")]
public class TrackingRecordController(
    ITrackingRecordService trackingRecordService,
    ILogger<TrackingRecordController> logger) : ControllerBase
{
    /// <summary>
    /// Retrieves a list of tracking records for the authenticated user.
    /// </summary>
    /// <param name="workItemId">Id of workitem of which records are tracking</param>
    /// <returns>A list of tracking records.</returns>
    /// <response code="200">Returns the list of tracking records.</response>
    /// <response code="401">If the user is not authenticated.</response>
    /// <response code="500">If there is an internal server error.</response>
    [HttpGet("{workItemId:int}")]
    [SwaggerOperation(Summary = "Retrieves a list of processes for the authenticated user.")]
    [ProducesResponseType(typeof(IReadOnlyCollection<TrackingRecordListItemDTO>), 200)]
    [ProducesResponseType(401)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetTrackingRecords([FromRoute] int workItemId)
    {
        string userName;

        try
        {
            userName = JwtTokenHelper.GetUserEmailFromToken(HttpContext);
            logger.LogInformation(
                "User {UserName} is attempting to retrieve tracking records for WorkItem {workItemId}", userName,
                workItemId);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Error retrieving user email from token.");
            return Unauthorized(new { message = "Invalid or missing token", error = ex.Message });
        }

        var result = await trackingRecordService.ListTrackingRecords(
            new TrackingRecordRequest(userName, workItemId));
        var response = ResponseMapper<List<TrackingRecordListItemDTO>>.MapServiceResponse(result);
        return response;
    }
}