using Aberwyn.Data;
using Microsoft.EntityFrameworkCore;
using WebPush;

namespace Aberwyn.Services
{
    public class PizzaNotificationService
    {
        private readonly ApplicationDbContext _context;
        private readonly PushNotificationService _push;

        public PizzaNotificationService(ApplicationDbContext context, PushNotificationService push)
        {
                Console.WriteLine("🍕 PizzaNotificationService constructor körs!");

            _context = context;
            _push = push;
        }

 public async Task<int> NotifyPizzaSubscribersAsync(string pizzaName = null, string userName = null)
{
    var title = "Ny pizzabeställning 🍕";
    var body = "En pizza har precis beställts!";

    if (!string.IsNullOrWhiteSpace(pizzaName))
        body = $"Pizzan '{pizzaName}' har precis beställts!";

    if (!string.IsNullOrWhiteSpace(userName))
        body += $" (av {userName})";

    var payload = $@"{{""title"":""{title}"",""body"":""{body}""}}";

    var subscribers = await _context.PushSubscribers
        .Include(s => s.User)
        .ThenInclude(u => u.Preferences)
        .Where(s => s.User != null &&
                    s.User.Preferences != null &&
                    s.User.Preferences.NotifyPizza &&
                    !string.IsNullOrEmpty(s.Endpoint) &&
                    s.Endpoint.StartsWith("https://"))
        .ToListAsync();

    var allSubscribers = await _context.PushSubscribers
    .Include(s => s.User)
    .ThenInclude(u => u.Preferences)
    .ToListAsync();
    foreach (var s in allSubscribers)
    {
        Console.WriteLine($"🔍 Sub: {s.Endpoint}, User: {s.User?.UserName}, NotifyPizza: {s.User?.Preferences?.NotifyPizza}");
    }
            int successCount = 0;
    foreach (var sub in subscribers)
    {
        try
        {
            _push.SendNotification(sub.Endpoint, sub.P256DH, sub.Auth, payload);
            successCount++;
        }
        catch (WebPushException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Gone || ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            Console.WriteLine($"🗑️ Ogiltig prenumeration tas bort: {sub.Endpoint}");
            _context.PushSubscribers.Remove(sub);
            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ Misslyckades att skicka till {sub.Endpoint}: {ex.Message}");
        }
    }


    return successCount;
}

    }
}
