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.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace adas_core.Controllers;


/// <summary>
/// Controller responsible for handling HTTP requests related to alarm observations.
/// Provides endpoints to retrieve, process, and manage alarm data.
/// </summary>
[Route("alarm-observations")]
[ApiController]
public class AlarmController : ControllerBase
{
    private readonly IAlarmService _alarmService;
    private readonly ILogger<AlarmController> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="AlarmController"/> class.
    /// </summary>
    /// <param name="logger">The logger instance used to log diagnostic and operational information for the controller.</param>
    /// <param name="alarmService">The alarm service instance used to perform alarm-related operations.</param>
    /// <exception cref="ArgumentNullException">Thrown when <paramref name="logger"/> or <paramref name="alarmService"/> is <c>null</c>.</exception>
    public AlarmController(ILogger<AlarmController> logger, IAlarmService alarmService)
    {
        LogExecutionContext.TrySetTraceIdentifier(Guid.NewGuid().ToString(), true);

        _logger = logger;

        _alarmService = alarmService;
    }

    /// <summary>
    /// Processes an incoming observation alarm request, constructing an <see cref="ApiRequest"/> from the provided DTO
    /// and delegating persistence to the alarm service. If the request indicates a synchronous result is expected,
    /// the request is saved synchronously; otherwise, it is saved asynchronously.
    /// </summary>
    /// <param name="alarmDto">The observation alarm data transfer object containing patient, location, alarm, and timing information.</param>
    /// <returns>An <see cref="IActionResult"/> containing the processed <see cref="ApiRequest"/> with HTTP 200 status.</returns>
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    [HttpPost]
    [Route("")]
    public IActionResult ProcessRequest([FromBody] ObservationAlarmDto alarmDto)
    {
        var request = new ApiRequest
        {
            TraceId = Guid.NewGuid().ToString(),
            Type = "ORU_R40",
            PatientNumber = alarmDto.PatientNumber,
            Location = alarmDto.Location,
            Alarms = alarmDto.Alarms,
            MessageTime = alarmDto.MessageTime,
            WaitResult = alarmDto.WaitResult,
            ObsertationData = alarmDto.ObservationData
        };

        _logger.LogDebug("Alarm received: {request}", request.ToString());

        if (request.WaitResult) _alarmService.SaveRequest(request);
        else _alarmService.SaveRequestAsync(request);
        return Ok(request);
    }
}