using MediatR;
using TakeoutSaaS.Application.App.Coupons.PunchCard.Commands;
using TakeoutSaaS.Application.App.Coupons.PunchCard.Dto;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Coupons.PunchCard.Handlers;

/// <summary>
/// 次卡状态变更处理器。
/// </summary>
public sealed class ChangePunchCardTemplateStatusCommandHandler(
    IPunchCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangePunchCardTemplateStatusCommand, PunchCardDetailDto>
{
    /// <inheritdoc />
    public async Task<PunchCardDetailDto> Handle(
        ChangePunchCardTemplateStatusCommand request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedStatus = PunchCardMapping.ParseTemplateStatus(request.Status);

        var entity = await repository.FindTemplateByIdAsync(
            tenantId,
            request.StoreId,
            request.TemplateId,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "次卡不存在");

        entity.Status = normalizedStatus;

        await repository.UpdateTemplateAsync(entity, cancellationToken);
        await repository.SaveChangesAsync(cancellationToken);

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

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

        return PunchCardDtoFactory.ToDetailDto(entity, aggregate);
    }
}
