using adas_core.Application.Services.Interfaces;
using adas_core.Authentication.Attributes;
using adas_core.Domain.Enums;
using adas_core.Logging;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebPush;

namespace adas_core.Controllers;

[Route("send-alerts")]
[ApiController]
public class SendAlertController : ControllerBase
{
    private readonly ISendAlertService _sendAlertService;

    public SendAlertController(ISendAlertService sendAlertService)
    {
        LogExecutionContext.TrySetTraceIdentifier(Guid.NewGuid().ToString(), true);

        _sendAlertService = sendAlertService;
    }

    public static List<PushSubscription> Subscriptions { get; set; } = [];

    [HttpGet("rabbit")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    public async Task<IActionResult> GetErrorQueues()
    {
        var errorQueues = await _sendAlertService.GetQueues();
        return Ok(errorQueues);
    }

    [HttpGet("performance")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    public IActionResult GetPerformance()
    {
        var performance = _sendAlertService.GetPerformance();
        return Ok(performance);
    }

    [HttpGet("api-clients")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    public async Task<IActionResult> GetApiClients()
    {
        var clients = await _sendAlertService.GetApiClients();
        return Ok(clients);
    }

    [HttpPost("web-subscribe")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    public IActionResult WebSubscribe([FromBody] PushSubscription sub)
    {
        Subscriptions.Add(sub);
        return Ok("correct subscription");
    }

    [HttpPost("web-unsubscribe")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    public IActionResult WebUnSubscribe([FromBody] PushSubscription sub)
    {
        var item = Subscriptions.FirstOrDefault(s => s.Endpoint == sub.Endpoint);
        if (item != null)
        {
            Subscriptions.Remove(item);
            return Ok("subscripcion correcta");
        }

        return Ok("failed subscription");
    }

    [HttpPost("broadcast/{sub}")]
    [AuthorizeRoles(PermissionEnum.RolesType.AuthAdmin)]
    public IActionResult Broadcast(string sub, [FromBody] object message)
    {
        var vapidDetails = new VapidDetails("mailto:example@example.com",
            "BJk9MGeoFy4npXPA6PQIgZYW5oxhiiBm_t2pB08FiotYQ4UvSaibG3T946Oqrc_nP17tdONbx0O4k9dWnt16TMM",
            "21YckusFRv00z1nOTpLZK1NlMXSZxZECnpwbsaKTjOE");

        var client = new WebPushClient();
        var serializedMessage = JsonConvert.SerializeObject(message);
        var pushSubscription = Subscriptions.FirstOrDefault(s => s.Endpoint == sub);

        if (pushSubscription == null)
            return NotFound("Subscription not found");

        client.SendNotification(pushSubscription, serializedMessage, vapidDetails);

        return Ok("correct subscription");
    }
}