using Aberwyn.Data;
using Aberwyn.Models;
using Lib.Net.Http.WebPush;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Aberwyn.Controllers
{
    [ApiController]
    [Route("api/push")]
    public class PushController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly PushNotificationService _notificationService;

        public PushController(ApplicationDbContext context, PushNotificationService notificationService)
        {
            _context = context;
            _notificationService = notificationService;
        }


        [HttpPost("subscribe")]
        public async Task<IActionResult> Subscribe([FromBody] PushSubscription subscription)
        {
            var existing = await _context.PushSubscribers
                .FirstOrDefaultAsync(s => s.Endpoint == subscription.Endpoint);

            if (existing == null)
            {
                var newSubscriber = new PushSubscriber
                {
                    Endpoint = subscription.Endpoint,
                    P256DH = subscription.Keys["p256dh"],
                    Auth = subscription.Keys["auth"]
                };

                _context.PushSubscribers.Add(newSubscriber);
            }
            else
            {
                existing.P256DH = subscription.Keys["p256dh"];
                existing.Auth = subscription.Keys["auth"];
            }
            await _context.SaveChangesAsync();

            return Ok();
        }

        [HttpGet("vapid-public-key")]
        public IActionResult GetVapidKey([FromServices] IConfiguration config)
        {
            var publicKey = config["VapidKeys:PublicKey"];
            return Content(publicKey);
        }

        [HttpPost("notify-all")]
        public async Task<IActionResult> NotifyAll([FromBody] PushMessageDto message)
        {
            if (string.IsNullOrWhiteSpace(message.Title) || string.IsNullOrWhiteSpace(message.Body))
            {
                return BadRequest("Titel och meddelande krävs.");
            }

            var subscribers = await _context.PushSubscribers.ToListAsync();
            var payload = $"{{\"title\":\"{message.Title}\",\"body\":\"{message.Body}\"}}";

            int successCount = 0;
            foreach (var sub in subscribers)
            {
                try
                {
                    _notificationService.SendNotification(sub.Endpoint, sub.P256DH, sub.Auth, payload);
                    successCount++;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"❌ Misslyckades att skicka till {sub.Endpoint}: {ex.Message}");
                }
            }

            return Ok($"Skickade notiser till {successCount} användare.");
        }

    }

}
