using System.Globalization;
using System.IO;
using System.Text;
using CsvHelper;
using SharepointToolbox.Core.Models;

namespace SharepointToolbox.Services.Export;

public class BulkResultCsvExportService
{
    public string BuildFailedItemsCsv<T>(IReadOnlyList<BulkItemResult<T>> failedItems)
    {
        using var writer = new StringWriter();
        using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);

        csv.WriteHeader<T>();
        csv.WriteField("Error");
        csv.WriteField("Timestamp");
        csv.NextRecord();

        foreach (var item in failedItems.Where(r => !r.IsSuccess))
        {
            csv.WriteRecord(item.Item);
            csv.WriteField(item.ErrorMessage);
            csv.WriteField(item.Timestamp.ToString("o"));
            csv.NextRecord();
        }

        return writer.ToString();
    }

    public async Task WriteFailedItemsCsvAsync<T>(
        IReadOnlyList<BulkItemResult<T>> failedItems,
        string filePath,
        CancellationToken ct)
    {
        var content = BuildFailedItemsCsv(failedItems);
        await System.IO.File.WriteAllTextAsync(filePath, content, new UTF8Encoding(true), ct);
    }
}
