using MediatR;
using TakeoutSaaS.Application.App.Members.StoredCard.Commands;
using TakeoutSaaS.Application.App.Members.StoredCard.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.StoredCard.Handlers;

/// <summary>
/// 修改储值卡方案状态处理器。
/// </summary>
public sealed class ChangeStoredCardPlanStatusCommandHandler(
    IStoredCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeStoredCardPlanStatusCommand, MemberStoredCardPlanDto>
{
    /// <inheritdoc />
    public async Task<MemberStoredCardPlanDto> Handle(
        ChangeStoredCardPlanStatusCommand request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var status = MemberStoredCardMapping.ParsePlanStatus(request.Status);

        var entity = await repository.FindPlanByIdAsync(
            tenantId,
            request.StoreId,
            request.PlanId,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "储值卡方案不存在");

        entity.Status = status;
        await repository.UpdatePlanAsync(entity, cancellationToken);
        await repository.SaveChangesAsync(cancellationToken);

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

        var aggregate = aggregates.TryGetValue(entity.Id, out var value)
            ? value
            : MemberStoredCardDtoFactory.EmptyAggregate(entity.Id);

        return MemberStoredCardDtoFactory.ToPlanDto(entity, aggregate);
    }
}
