using MediatR;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Security;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 公告详情查询处理器。
/// </summary>
public sealed class GetTenantAnnouncementQueryHandler(
    ITenantAnnouncementRepository announcementRepository,
    ITenantAnnouncementReadRepository readRepository,
    ICurrentUserAccessor? currentUserAccessor = null)
    : IRequestHandler<GetTenantAnnouncementQuery, TenantAnnouncementDto?>
{
    /// <summary>
    /// 查询公告详情。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>公告 DTO 或 null。</returns>
    public async Task<TenantAnnouncementDto?> Handle(GetTenantAnnouncementQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询公告主体
        var announcement = await announcementRepository.FindByIdAsync(request.TenantId, request.AnnouncementId, cancellationToken);
        if (announcement == null)
        {
            return null;
        }

        // 2. 优先查用户级已读
        var userId = currentUserAccessor?.UserId ?? 0;
        var reads = await readRepository.GetByAnnouncementAsync(
            request.TenantId,
            new[] { request.AnnouncementId },
            userId == 0 ? null : userId,
            cancellationToken);

        // 如无用户级已读，再查租户级已读
        if (reads.Count == 0)
        {
            var tenantReads = await readRepository.GetByAnnouncementAsync(request.TenantId, new[] { request.AnnouncementId }, null, cancellationToken);
            reads = tenantReads;
        }

        // 3. 返回 DTO 并附带已读状态
        var readRecord = reads.FirstOrDefault();
        return announcement.ToDto(readRecord != null, readRecord?.ReadAt);
    }
}
