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 ChangeProductCategoryStatusCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<ChangeProductCategoryStatusCommand, ProductCategoryManageItemDto>
{
    /// <inheritdoc />
    public async Task<ProductCategoryManageItemDto> Handle(ChangeProductCategoryStatusCommand request, CancellationToken cancellationToken)
    {
        if (!ProductCategoryManageMapping.TryParseStatus(request.Status, out var isEnabled))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
        }

        var tenantId = tenantProvider.GetCurrentTenantId();
        var category = await productRepository.FindCategoryByIdAsync(request.CategoryId, tenantId, cancellationToken);
        if (category is null || category.StoreId != request.StoreId)
        {
            throw new BusinessException(ErrorCodes.NotFound, "分类不存在");
        }

        category.IsEnabled = isEnabled;
        await productRepository.UpdateCategoryAsync(category, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);

        var productCounts = await productRepository.CountProductsByCategoryIdsAsync(
            tenantId,
            request.StoreId,
            [category.Id],
            cancellationToken);

        return new ProductCategoryManageItemDto
        {
            Id = category.Id,
            Name = category.Name,
            Sort = category.SortOrder,
            ProductCount = productCounts.GetValueOrDefault(category.Id),
            Description = category.Description ?? string.Empty,
            Icon = category.Icon ?? string.Empty,
            Status = ProductCategoryManageMapping.ToStatusText(category.IsEnabled),
            Channels = ProductCategoryManageMapping.DeserializeChannels(category.ChannelsJson)
        };
    }
}
