using salesbook.Shared.Core.Dto.PageState;
using salesbook.Shared.Core.Interface;
using salesbook.Shared.Core.Interface.IntegryApi;

namespace salesbook.Shared.Core.Services;

public class NotificationService(
    IIntegryNotificationRestClient integryNotificationRestClient,
    NotificationState Notification
) : INotificationService
{
    public async Task LoadNotification()
    {
        var allNotifications = await integryNotificationRestClient.Get();
        if (allNotifications == null) return;
        
        var allIds = allNotifications.Select(n => n.Id).ToHashSet();

        Notification.ReceivedNotifications = Notification.ReceivedNotifications
            .Where(r => !allIds.Contains(r.Id))
            .ToList();

        Notification.UnreadNotifications = allNotifications
            .Where(x =>
                x.WtbDeviceNotifications == null ||
                x.WtbDeviceNotifications.Any(y => y.ReadDate == null))
            .ToList();

        Notification.NotificationsRead = allNotifications
            .Where(x =>
                x.WtbDeviceNotifications != null &&
                x.WtbDeviceNotifications.All(y => y.ReadDate != null))
            .ToList();
    }

    public void OrderNotificationList()
    {
        Notification.ReceivedNotifications = Notification.ReceivedNotifications
            .OrderByDescending(x => x.StartDate).ToList();

        Notification.UnreadNotifications = Notification.UnreadNotifications
            .OrderByDescending(x => x.StartDate).ToList();

        Notification.NotificationsRead = Notification.NotificationsRead
            .OrderByDescending(x => x.StartDate).ToList();
    }
}