using adas_core.Application.Services.Interfaces;
using adas_core.Authentication.Attributes;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.DTO;
using adas_core.Logging;
using Microsoft.AspNetCore.Mvc;

namespace adas_core.Controllers;

/// <summary>
/// HTTP API controller that exposes endpoints related to recording alerts under the alerts route.
/// </summary>
/// <remarks>
/// Configured with <see cref="ApiControllerAttribute"/> and <see cref="RouteAttribute"/> and inherits from <see cref="ControllerBase"/>.</remarks>
/// <!-- aidoc:v1 sig=48c6dd9 -->
[Route("alerts")]
[ApiController]
public class RecordingAlertController : ControllerBase
{
    private readonly IRecordingAlertService _recordingAlertService;

    /// <summary>
    /// Initializes a new instance of the <see cref="RecordingAlertController"/> class with the specified recording alert service.
    /// </summary>
    /// <param name="recordingAlertService"> The service that handles the recording alert operations.</param> 
    /// <!-- aidoc:v1 sig=860fe32 body=842e180 -->
    public RecordingAlertController(IRecordingAlertService recordingAlertService)
    {
        LogExecutionContext.TrySetTraceIdentifier(Guid.NewGuid().ToString(), true);

        _recordingAlertService = recordingAlertService;
    }


    /// <summary>
    /// Processes an incoming recording alert request by mapping the incoming DTO to an internal API request and persisting it either synchronously or asynchronously based on whether the caller requires a result.
    /// </summary>
    /// <param name="recordingAlertDto">The recording alert payload containing the patient number, location, recording alerts, recording data, message time, and a flag indicating whether the operation should wait for completion.</param>
    /// <!-- aidoc:v1 sig=9fd7813 body=096e423 -->
    [HttpPost]
    [Route("")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthSome)]
    [PermissionAuthorize("Source", "DisplayId")]
    public IActionResult ProcessRequest([FromBody] RecordingAlertDto recordingAlertDto)
    {
        var request = new ApiRequest
        {
            TraceId = Guid.NewGuid().ToString(),
            Type = "RecordingAlert",
            PatientNumber = recordingAlertDto.PatientNumber,
            Location = recordingAlertDto.Location,
            RecordingAlerts = recordingAlertDto.RecordingAlerts,
            Recording = recordingAlertDto.RecordingData,
            MessageTime = recordingAlertDto.MessageTime,
            WaitResult = recordingAlertDto.WaitResult
        };

        if (request.WaitResult) _recordingAlertService.SaveRequest(request);
        else _recordingAlertService.SaveRequestAsync(request);

        return Ok();
    }
}