using MediatR;
using TakeoutSaaS.Application.App.Coupons.Dto;
using TakeoutSaaS.Application.App.Coupons.Queries;
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.Handlers;

/// <summary>
/// 优惠券模板详情查询处理器。
/// </summary>
public sealed class GetCouponTemplateDetailQueryHandler(
    ICouponRepository couponRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetCouponTemplateDetailQuery, CouponTemplateDetailDto?>
{
    /// <inheritdoc />
    public async Task<CouponTemplateDetailDto?> Handle(GetCouponTemplateDetailQuery request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var template = await couponRepository.FindTemplateByIdAsync(request.TemplateId, tenantId, cancellationToken);
        if (template is null)
        {
            return null;
        }

        var scope = CouponTemplateMapping.DeserializeStoreScope(template.StoreScopeJson, template.Id);
        if (!scope.StoreIds.Contains(request.StoreId) && !string.Equals(scope.Mode, "all", StringComparison.Ordinal))
        {
            throw new BusinessException(ErrorCodes.NotFound, "优惠券不存在");
        }

        var channels = CouponTemplateMapping.DeserializeChannels(template.ChannelsJson, template.Id);
        return CouponTemplateDtoFactory.ToDetailDto(template, scope, channels);
    }
}
