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

/// <summary>
/// 删除积分商城商品处理器。
/// </summary>
public sealed class DeletePointMallProductCommandHandler(
    IPointMallRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeletePointMallProductCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeletePointMallProductCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();

        var product = await repository.FindProductByIdAsync(
            tenantId,
            request.StoreId,
            request.PointMallProductId,
            cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "兑换商品不存在");

        var hasRecords = await repository.HasRecordsByProductIdAsync(
            tenantId,
            request.StoreId,
            request.PointMallProductId,
            cancellationToken);

        if (hasRecords)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "存在兑换记录的商品不允许删除");
        }

        await repository.DeleteProductAsync(product, cancellationToken);
        await repository.SaveChangesAsync(cancellationToken);
    }
}
