using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 删除商品标签命令处理器。
/// </summary>
public sealed class DeleteProductLabelCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteProductLabelCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteProductLabelCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验标签存在且归属当前门店。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await productRepository.FindLabelByIdAsync(request.LabelId, tenantId, cancellationToken);
        if (existing is null || existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.NotFound, "标签不存在");
        }

        // 2. 删除关联与标签主记录。
        await productRepository.RemoveLabelProductsAsync(existing.Id, tenantId, request.StoreId, cancellationToken);
        await productRepository.DeleteLabelAsync(existing.Id, tenantId, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
    }
}
