using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Application.App.Products.Queries;
using TakeoutSaaS.Domain.Products.Enums;
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 PublishProductCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider,
    ILogger<PublishProductCommandHandler> logger)
    : IRequestHandler<PublishProductCommand, ProductDto?>
{
    /// <inheritdoc />
    public async Task<ProductDto?> Handle(PublishProductCommand request, CancellationToken cancellationToken)
    {
        // 1. 读取商品
        var tenantId = tenantProvider.GetCurrentTenantId();
        var product = await productRepository.FindByIdAsync(request.ProductId, tenantId, cancellationToken);
        if (product is null)
        {
            return null;
        }

        // 2. 校验 SKU 可售
        var skus = await productRepository.GetSkusAsync(product.Id, tenantId, cancellationToken);
        if (skus.Count == 0)
        {
            throw new BusinessException(ErrorCodes.Conflict, "请先配置可售 SKU 后再上架");
        }

        // 3. 上架
        product.Status = ProductStatus.OnSale;
        await productRepository.UpdateProductAsync(product, cancellationToken);
        await productRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("商品上架 {ProductId}", product.Id);

        return ProductMapping.ToDto(product);
    }
}
