using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 标记通知已读处理器。
/// </summary>
public sealed class MarkTenantNotificationReadCommandHandler(
    ITenantNotificationRepository notificationRepository,
    ITenantProvider tenantProvider)
    : 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 currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 兼容旧调用：若传入 TenantId，则必须与当前租户一致
        if (request.TenantId > 0 && request.TenantId != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "无权标记其他租户通知");
        }

        // 3. (空行后) 查询通知
        var notification = await notificationRepository.FindByIdAsync(currentTenantId, request.NotificationId, cancellationToken);
        if (notification == null)
        {
            return null;
        }

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

        // 5. (空行后) 返回 DTO
        return notification.ToDto();
    }
}
