using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using StellaOps.Feedser.Core.Jobs;
using StellaOps.Feedser.Merge.Services;

namespace StellaOps.Feedser.Merge.Jobs;

public sealed class MergeReconcileJob : IJob
{
    private readonly AdvisoryMergeService _mergeService;
    private readonly ILogger<MergeReconcileJob> _logger;

    public MergeReconcileJob(AdvisoryMergeService mergeService, ILogger<MergeReconcileJob> logger)
    {
        _mergeService = mergeService ?? throw new ArgumentNullException(nameof(mergeService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task ExecuteAsync(JobExecutionContext context, CancellationToken cancellationToken)
    {
        if (!context.Parameters.TryGetValue("seed", out var seedValue) || seedValue is not string seed || string.IsNullOrWhiteSpace(seed))
        {
            context.Logger.LogWarning("merge:reconcile job requires a non-empty 'seed' parameter.");
            return;
        }

        var result = await _mergeService.MergeAsync(seed, cancellationToken).ConfigureAwait(false);
        if (result.Merged is null)
        {
            _logger.LogInformation("No advisories available to merge for alias component seeded by {Seed}", seed);
            return;
        }

        _logger.LogInformation(
            "Merged alias component seeded by {Seed} into canonical {Canonical} using {Count} advisories; collisions={Collisions}",
            seed,
            result.CanonicalAdvisoryKey,
            result.Inputs.Count,
            result.Component.Collisions.Count);
    }
}
