
using System.Data;

using CSharpFunctionalExtensions;

using OfficeOpenXml;

namespace Monitoring.Features.Reports.FileBuilders;

public class ExcelFileBuilder : IFileBuilder
{
	public async ValueTask<Result<byte[]>> Create(
		DataTable table, CancellationToken cancellationToken)
	{
		try
		{
			ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

			using ExcelPackage package = new();
			var worksheet = package.Workbook.Worksheets.Add("Report");

			AddHeaders(worksheet, table);

			_ = worksheet.Cells["A2"].LoadFromDataTable(table);

			worksheet.Cells.AutoFitColumns();

			using MemoryStream outputStream = new();
			await package.SaveAsAsync(outputStream, cancellationToken);
			return outputStream.ToArray();
		}
		catch (Exception ex)
		{
			return Result.Failure<byte[]>(ex.Message);
		}
	}

	private static void AddHeaders(ExcelWorksheet worksheet, DataTable table)
	{
		for (var i = 0; i < table.Columns.Count; i++)
		{
			_ = worksheet.Cells[1, i + 1].Value = table.Columns[i].ColumnName;
		}
	}
}