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 DeleteProductScheduleCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<DeleteProductScheduleCommand>
{
    /// <inheritdoc />
    public async Task Handle(DeleteProductScheduleCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验规则存在且归属当前门店。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var existing = await productRepository.FindScheduleByIdAsync(request.ScheduleId, tenantId, cancellationToken);
        if (existing is null || existing.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.NotFound, "时段规则不存在");
        }

        // 2. 删除关联和主记录。
        await productRepository.RemoveScheduleProductsAsync(existing.Id, tenantId, request.StoreId, cancellationToken);
        await productRepository.DeleteScheduleAsync(existing.Id, tenantId, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
    }
}
