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;

[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> 
    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>
    [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();
    }
}