using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Services;

/// <summary>
/// In-app notifications. When a new shift/job is published, notifies users whose saved
/// preferences match it (role / city / — for shifts — shift type). Users with no preference set
/// are NOT notified (avoids spamming everyone). One notification per matching user.
/// </summary>
public class NotificationService
{
    private readonly AppDbContext _db;
    private readonly PushNotifier _push;
    private readonly NotificationHub _hub;
    private readonly ILogger<NotificationService> _log;

    public NotificationService(AppDbContext db, PushNotifier push, NotificationHub hub, ILogger<NotificationService> log)
    {
        _db = db;
        _push = push;
        _hub = hub;
        _log = log;
    }

    public Task<int> UnreadCountAsync(int userId) =>
        _db.Notifications.CountAsync(n => n.UserId == userId && !n.IsRead);

    public Task<List<Notification>> ListAsync(int userId, int take = 50) =>
        _db.Notifications.Where(n => n.UserId == userId)
            .OrderByDescending(n => n.CreatedAt).Take(take).ToListAsync();

    public async Task MarkAllReadAsync(int userId) =>
        await _db.Notifications.Where(n => n.UserId == userId && !n.IsRead)
            .ExecuteUpdateAsync(s => s.SetProperty(n => n.IsRead, true));

    /// <summary>Admin broadcast: notify a set of users (in-app + push) with a custom message.</summary>
    public Task BroadcastAsync(IReadOnlyCollection<int> userIds, string title, string? body, string? url)
        => AddAsync(userIds.ToList(), title, body, url ?? "/");

    public async Task NotifyNewShiftAsync(int shiftId)
    {
        var s = await _db.Shifts.Include(x => x.Facility).Include(x => x.Role)
            .FirstOrDefaultAsync(x => x.Id == shiftId);
        if (s is null) return;

        var users = await MatchingUserIdsAsync(s.RoleId, s.Facility.CityId, s.ShiftType);
        var title = $"شیفت جدید: {s.Role.Name}";
        var body = $"{s.Facility.Name} — {JalaliDate.WeekDayName(s.Date)} {JalaliDate.Time(s.StartTime)}";
        await AddAsync(users, title, body, $"/Shifts/Details/{s.Id}");
    }

    public async Task NotifyNewJobAsync(int jobId)
    {
        var j = await _db.JobOpenings.Include(x => x.Facility).Include(x => x.Role)
            .FirstOrDefaultAsync(x => x.Id == jobId);
        if (j is null) return;

        var users = await MatchingUserIdsAsync(j.RoleId, j.Facility.CityId, null);
        await AddAsync(users, $"استخدام جدید: {j.Title}", j.Facility.Name, $"/Jobs/Details/{j.Id}");
    }

    /// <summary>Users with a non-empty preference that matches the listing (via their visitor link).</summary>
    private async Task<List<int>> MatchingUserIdsAsync(int roleId, int cityId, ShiftType? shiftType)
    {
        var q = from up in _db.UserPreferences
                join v in _db.Visitors on up.VisitorId equals v.Id
                where v.UserId != null
                    && (up.RoleId != null || up.CityId != null)            // must have a real preference
                    && (up.RoleId == null || up.RoleId == roleId)
                    && (up.CityId == null || up.CityId == cityId)
                    && (shiftType == null || up.PreferredShiftType == null || up.PreferredShiftType == shiftType)
                select v.UserId!.Value;
        return await q.Distinct().ToListAsync();
    }

    private async Task AddAsync(List<int> userIds, string title, string? body, string url)
    {
        if (userIds.Count == 0) return;

        var settings = await _db.AppSettings.FindAsync(1);
        var webOn = settings?.WebNotificationsEnabled ?? true;   // master toggle for the in-app/web channel

        // Web / in-app notifications channel (bell list + live SSE). Admin can turn it off.
        if (webOn)
        {
            foreach (var uid in userIds)
                _db.Notifications.Add(new Notification { UserId = uid, Title = title, Body = body, Url = url });
            await _db.SaveChangesAsync();
            _log.LogInformation("Notified {Count} users: {Title}", userIds.Count, title);

            // Live: stream to any open tab/PWA over SSE (our own origin — works in Iran).
            // The browser updates the bell instantly + shows a local toast/OS notification.
            var notice = new LiveNotice(title, body, url);
            foreach (var uid in userIds) _hub.Publish(uid, notice);
        }

        // Web Push channel (lock screen). Self-gates on PushEnabled + VAPID keys; best-effort
        // since Web Push depends on the browser's push service, which is filtered in Iran.
        try { await _push.PushToUsersAsync(userIds, title, body, url); }
        catch (Exception ex) { _log.LogWarning(ex, "Web push fan-out failed"); }
    }
}
