using System.Collections.Concurrent;
using Hc900Crawler.Core.Application.Feedforward;

namespace Hc900Crawler.Infrastructure.Control;

/// <summary>작업 B: 컬럼별 활성 FEED 램프 작업 인메모리 저장소(싱글턴).</summary>
public sealed class FeedRampJobStore : IFeedRampJobStore
{
    private readonly ConcurrentDictionary<int, FeedRampJob> _jobs = new();

    public FeedRampJob Start(int columnId, double targetFeed, string op, bool dryRun)
    {
        var job = new FeedRampJob
        {
            ColumnId   = columnId,
            TargetFeed = targetFeed,
            State      = FeedRampState.Ramping,
            StartedAt  = DateTime.UtcNow,
            Operator   = op,
            DryRun     = dryRun
        };
        _jobs[columnId] = job;
        return job;
    }

    public FeedRampJob? Get(int columnId) => _jobs.TryGetValue(columnId, out var j) ? j : null;

    public IReadOnlyCollection<FeedRampJob> GetAll() => _jobs.Values.ToArray();

    public void Update(FeedRampJob job) => _jobs[job.ColumnId] = job;

    public bool Cancel(int columnId)
    {
        if (!_jobs.TryGetValue(columnId, out var j)) return false;
        _jobs[columnId] = j with { State = FeedRampState.Canceled };
        return true;
    }
}
