using MassTransit;
using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Application.App.Products.Messaging;
using TakeoutSaaS.Domain.Products.Enums;
using TakeoutSaaS.Infrastructure.App.Persistence;
using TakeoutSaaS.TenantApi.Services;

namespace TakeoutSaaS.SkuWorker.Consumers;

/// <summary>
/// SKU 保存任务消费器。
/// </summary>
public sealed class ProductSkuSaveJobRequestedConsumer(
    ProductSkuSaveJobRunner jobRunner,
    TakeoutAppDbContext dbContext,
    ILogger<ProductSkuSaveJobRequestedConsumer> logger) : IConsumer<ProductSkuSaveJobRequestedEvent>
{
    /// <inheritdoc />
    public async Task Consume(ConsumeContext<ProductSkuSaveJobRequestedEvent> context)
    {
        var payload = context.Message;
        logger.LogInformation(
            "开始消费 SKU 保存任务，JobId={JobId}, TenantId={TenantId}, StoreId={StoreId}, ProductId={ProductId}, RetryAttempt={RetryAttempt}",
            payload.JobId,
            payload.TenantId,
            payload.StoreId,
            payload.ProductId,
            context.GetRetryAttempt());

        await jobRunner.ExecuteAsync(payload.JobId);

        var jobStatus = await dbContext.ProductSkuSaveJobs
            .IgnoreQueryFilters()
            .AsNoTracking()
            .Where(item => item.Id == payload.JobId)
            .Select(item => item.Status)
            .SingleOrDefaultAsync(context.CancellationToken);

        if (jobStatus == ProductSkuSaveJobStatus.Failed)
        {
            throw new InvalidOperationException($"SKU 保存任务执行失败，JobId={payload.JobId}");
        }
    }
}
