
using System.Data;
using System.IO.Compression;

using CSharpFunctionalExtensions;

namespace Monitoring.Features.Reports.FileBuilders;

public class ZipFileBuilder : IFileBuilder
{
	public async ValueTask<Result<byte[]>> Create(DataTable table, CancellationToken cancellationToken)
	{
		try
		{
			using MemoryStream memoryStream = new();
			using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
			{
				IFileBuilder builder = new PdfFileBuilder();
				var result = await builder.Create(table, cancellationToken);
				if (result.IsFailure)
				{
					return result;
				}

				var entry = archive.CreateEntry("Report.pdf");
				using (var stream = entry.Open())
				{
					await stream.WriteAsync(result.Value, cancellationToken);
				}

				builder = new ExcelFileBuilder();
				result = await builder.Create(table, cancellationToken);
				if (result.IsFailure)
				{
					return result;
				}

				entry = archive.CreateEntry("Report.xlsx");
				using (var stream2 = entry.Open())
				{
					await stream2.WriteAsync(result.Value, cancellationToken);
				}
			}

			return Result.Success(memoryStream.ToArray());
		}
		catch (Exception ex)
		{
			return Result.Failure<byte[]>(ex.Message);
		}
	}
}