using Exam.Infrastructure.Extensions;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Snapshot.Contracts;
using Hotline.Snapshot.IRepository;
using Mapster;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Dependency;

namespace Hotline.Snapshot.Services;

public class NotificationDomainService : INotificationDomainService, IScopeDependency
{
    private readonly INotificationRepository _notificationRepository;
    private readonly INotificationReceiverRepository _notificationReceiverRepository;
    private readonly ILogger<NotificationDomainService> _logger;

    public NotificationDomainService(INotificationRepository notificationRepository, INotificationReceiverRepository notificationReceiverRepository, ILogger<NotificationDomainService> logger)
    {
        _notificationRepository = notificationRepository;
        _notificationReceiverRepository = notificationReceiverRepository;
        _logger = logger;
    }

    public async Task AddNotifyAsync(AddNotifyInDto inDto, CancellationToken token)
    {
        var entity = inDto.Adapt<Notification>();
        var hasOld = await _notificationRepository.Queryable()
            .Where(m => m.ExternalId == inDto.ExternalId)
            .AnyAsync();
        if (hasOld) 
        {
            _logger.LogInformation("通知消息已存在, 不重复通知用户. " + inDto.ToJson());
            return;
        }
        var id = await _notificationRepository.AddAsync(entity, token);
        var items = new List<NotificationReceiver>();
        foreach (var userId in inDto.UserIds)
        {
            items.Add(new NotificationReceiver { 
                NotificationId = id,
                ReceiverId = userId,
                IsRead = false
            });
        }
        await _notificationReceiverRepository.AddRangeAsync(items, token);
    }
}
