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 DeleteProductAddonGroupCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteProductAddonGroupCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteProductAddonGroupCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验加料组是否存在且归属当前门店。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await productRepository.FindAddonTemplateByIdAsync(request.GroupId, tenantId, cancellationToken);
        if (existing is null || existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.NotFound, "加料组不存在");
        }

        // 2. 删除选项、关联商品和模板主记录。
        await productRepository.RemoveSpecTemplateOptionsAsync(existing.Id, tenantId, cancellationToken);
        await productRepository.RemoveSpecTemplateProductsAsync(existing.Id, tenantId, request.StoreId, cancellationToken);
        await productRepository.DeleteSpecTemplateAsync(existing.Id, tenantId, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
    }
}
