using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 标记通知已读处理器。
/// </summary>
public sealed class MarkTenantNotificationReadCommandHandler(ITenantNotificationRepository notificationRepository)
    : IRequestHandler<MarkTenantNotificationReadCommand, TenantNotificationDto?>
{
    /// <summary>
    /// 标记通知已读。
    /// </summary>
    /// <param name="request">标记命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>通知 DTO 或 null。</returns>
    public async Task<TenantNotificationDto?> Handle(MarkTenantNotificationReadCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询通知
        var notification = await notificationRepository.FindByIdAsync(request.TenantId, request.NotificationId, cancellationToken);
        if (notification == null)
        {
            return null;
        }

        // 2. 若未读则标记已读
        if (notification.ReadAt == null)
        {
            notification.ReadAt = DateTime.UtcNow;
            await notificationRepository.UpdateAsync(notification, cancellationToken);
            await notificationRepository.SaveChangesAsync(cancellationToken);
        }

        // 3. 返回 DTO
        return notification.ToDto();
    }
}
