using SharepointToolbox.Core.Models;

namespace SharepointToolbox.Services;

public static class BulkOperationRunner
{
    /// <summary>
    /// Runs a bulk operation with continue-on-error semantics, per-item result tracking,
    /// and cancellation support. OperationCanceledException propagates immediately.
    /// </summary>
    public static async Task<BulkOperationSummary<TItem>> RunAsync<TItem>(
        IReadOnlyList<TItem> items,
        Func<TItem, int, CancellationToken, Task> processItem,
        IProgress<OperationProgress> progress,
        CancellationToken ct)
    {
        var results = new List<BulkItemResult<TItem>>();
        for (int i = 0; i < items.Count; i++)
        {
            ct.ThrowIfCancellationRequested();
            progress.Report(new OperationProgress(i + 1, items.Count, $"Processing {i + 1}/{items.Count}..."));
            try
            {
                await processItem(items[i], i, ct);
                results.Add(BulkItemResult<TItem>.Success(items[i]));
            }
            catch (OperationCanceledException) { throw; }
            catch (Exception ex)
            {
                results.Add(BulkItemResult<TItem>.Failed(items[i], ex.Message));
            }
        }
        progress.Report(new OperationProgress(items.Count, items.Count, "Complete."));
        return new BulkOperationSummary<TItem>(results);
    }
}
