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 SaveStoredCardPlanCommandHandler(
    IStoredCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SaveStoredCardPlanCommand, MemberStoredCardPlanDto>
{
    /// <inheritdoc />
    public async Task<MemberStoredCardPlanDto> Handle(
        SaveStoredCardPlanCommand request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedRechargeAmount = MemberStoredCardMapping.NormalizeRechargeAmount(request.RechargeAmount);
        var normalizedGiftAmount = MemberStoredCardMapping.NormalizeGiftAmount(request.GiftAmount);
        var normalizedSortOrder = MemberStoredCardMapping.NormalizeSortOrder(request.SortOrder);
        var status = MemberStoredCardMapping.ParsePlanStatus(request.Status);

        var allPlans = await repository.GetPlansByStoreAsync(
            tenantId,
            request.StoreId,
            cancellationToken);

        var duplicated = allPlans.Any(item =>
            item.Id != request.PlanId &&
            item.RechargeAmount == normalizedRechargeAmount &&
            item.GiftAmount == normalizedGiftAmount);

        if (duplicated)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "已存在相同充值金额与赠送金额的方案");
        }

        Domain.Membership.Entities.MemberStoredCardPlan entity;
        if (request.PlanId.HasValue && request.PlanId.Value > 0)
        {
            entity = await repository.FindPlanByIdAsync(
                tenantId,
                request.StoreId,
                request.PlanId.Value,
                cancellationToken)
                ?? throw new BusinessException(ErrorCodes.NotFound, "储值卡方案不存在");

            entity.RechargeAmount = normalizedRechargeAmount;
            entity.GiftAmount = normalizedGiftAmount;
            entity.SortOrder = normalizedSortOrder;
            entity.Status = status;

            await repository.UpdatePlanAsync(entity, cancellationToken);
        }
        else
        {
            entity = MemberStoredCardDtoFactory.CreatePlanEntity(
                request,
                normalizedRechargeAmount,
                normalizedGiftAmount,
                normalizedSortOrder,
                status);

            await repository.AddPlanAsync(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);
    }
}
