using MediatR;
using TakeoutSaaS.Application.App.Members.PointsMall.Dto;
using TakeoutSaaS.Application.App.Members.PointsMall.Queries;
using TakeoutSaaS.Domain.Membership.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Members.PointsMall.Handlers;

/// <summary>
/// 查询积分商城商品详情处理器。
/// </summary>
public sealed class GetPointMallProductDetailQueryHandler(
    IPointMallRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetPointMallProductDetailQuery, MemberPointMallProductDto>
{
    /// <inheritdoc />
    public async Task<MemberPointMallProductDto> Handle(
        GetPointMallProductDetailQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();

        var product = await repository.GetProductByIdAsync(
            tenantId,
            request.StoreId,
            request.PointMallProductId,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "兑换商品不存在");

        var aggregates = await repository.GetProductAggregatesAsync(
            tenantId,
            request.StoreId,
            [product.Id],
            cancellationToken);

        var aggregate = aggregates.TryGetValue(product.Id, out var value)
            ? value
            : MemberPointMallDtoFactory.EmptyProductAggregate(product.Id);

        return MemberPointMallDtoFactory.ToProductDto(product, aggregate);
    }
}
