using MediatR;
using TakeoutSaaS.Application.App.Members.PointsMall.Commands;
using TakeoutSaaS.Application.App.Members.PointsMall.Dto;
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 ChangePointMallProductStatusCommandHandler(
    IPointMallRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangePointMallProductStatusCommand, MemberPointMallProductDto>
{
    /// <inheritdoc />
    public async Task<MemberPointMallProductDto> Handle(
        ChangePointMallProductStatusCommand request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var status = MemberPointMallMapping.ParseProductStatus(request.Status);

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

        product.Status = status;
        await repository.UpdateProductAsync(product, cancellationToken);
        await repository.SaveChangesAsync(cancellationToken);

        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);
    }
}
