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 DeleteProductSpecTemplateCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteProductSpecTemplateCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteProductSpecTemplateCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验模板是否存在且归属当前门店。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await productRepository.FindSpecTemplateByIdAsync(request.SpecId, 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);
    }
}
