using MediatR;
using TakeoutSaaS.Application.App.Coupons.PunchCard.Dto;
using TakeoutSaaS.Application.App.Coupons.PunchCard.Queries;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

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

/// <summary>
/// 次卡模板详情查询处理器。
/// </summary>
public sealed class GetPunchCardTemplateDetailQueryHandler(
    IPunchCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetPunchCardTemplateDetailQuery, PunchCardDetailDto?>
{
    /// <inheritdoc />
    public async Task<PunchCardDetailDto?> Handle(
        GetPunchCardTemplateDetailQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();

        var template = await repository.FindTemplateByIdAsync(
            tenantId,
            request.StoreId,
            request.TemplateId,
            cancellationToken);

        if (template is null)
        {
            return null;
        }

        var aggregate = await repository.GetTemplateAggregateByTemplateIdsAsync(
            tenantId,
            request.StoreId,
            [request.TemplateId],
            cancellationToken);

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

        return PunchCardDtoFactory.ToDetailDto(template, snapshot);
    }
}
