using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
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 ChangeProductLabelStatusCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeProductLabelStatusCommand, ProductLabelItemDto>
{
    /// <inheritdoc />
    public async Task<ProductLabelItemDto> Handle(ChangeProductLabelStatusCommand request, CancellationToken cancellationToken)
    {
        // 1. 解析状态并校验标签归属。
        if (!ProductLabelMapping.TryParseStatus(request.Status, out var isEnabled))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        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. 保存状态变更。
        existing.IsEnabled = isEnabled;
        await productRepository.UpdateLabelAsync(existing, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);

        // 3. 返回最新快照。
        var productCounts = await productRepository.CountLabelProductsByLabelIdsAsync(
            tenantId,
            request.StoreId,
            [existing.Id],
            cancellationToken);
        return ProductLabelDtoFactory.ToDto(existing, productCounts);
    }
}
