using CashLineERP.Contracts.Tax;
using System.IO.Compression;
using System.Text;
using System.Text.Json;

namespace CashLineERP.Api.Infrastructure;

internal static class ExportFileResultFactory
{
    public static IResult FromText(string contentText, string contentType, string fileName) =>
        Results.File(Encoding.UTF8.GetBytes(contentText), contentType, fileName);

    public static IResult FromPackage(FinanceReviewExportPackageResponse package)
    {
        using var stream = new MemoryStream();
        using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
        {
            foreach (var entry in package.Entries)
            {
                var zipEntry = archive.CreateEntry(entry.FileName, CompressionLevel.Fastest);
                using var entryStream = zipEntry.Open();
                using var writer = new StreamWriter(entryStream, Encoding.UTF8);
                writer.Write(entry.ContentText);
            }

            var manifestEntry = archive.CreateEntry("manifest.json", CompressionLevel.Fastest);
            using var manifestStream = manifestEntry.Open();
            using var manifestWriter = new StreamWriter(manifestStream, Encoding.UTF8);
            manifestWriter.Write(JsonSerializer.Serialize(new
            {
                package.DocumentType,
                package.DocumentId,
                package.DocumentNumber,
                package.ExportedAtUtc,
                entries = package.Entries.Select(entry => new
                {
                    entry.EntryCode,
                    entry.FileName,
                    entry.ContentType
                })
            }, new JsonSerializerOptions { WriteIndented = true }));
        }

        return Results.File(stream.ToArray(), "application/zip", package.PackageFileName);
    }
}
