using MediatR;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 商户审核领取信息查询处理器。
/// </summary>
public sealed class GetMerchantReviewClaimQueryHandler(IMerchantRepository merchantRepository)
    : IRequestHandler<GetMerchantReviewClaimQuery, ClaimInfoDto?>
{
    /// <inheritdoc />
    public async Task<ClaimInfoDto?> Handle(GetMerchantReviewClaimQuery request, CancellationToken cancellationToken)
    {
        var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");

        if (!merchant.ClaimedBy.HasValue)
        {
            return null;
        }

        if (merchant.ClaimExpiresAt.HasValue && merchant.ClaimExpiresAt <= DateTime.UtcNow)
        {
            return null;
        }

        return new ClaimInfoDto
        {
            MerchantId = merchant.Id,
            ClaimedBy = merchant.ClaimedBy,
            ClaimedByName = merchant.ClaimedByName,
            ClaimedAt = merchant.ClaimedAt,
            ClaimExpiresAt = merchant.ClaimExpiresAt
        };
    }
}
