using System.Text.RegularExpressions;
using ClosedXML.Excel;
using SolutionErp.Application.Forms.Services;

namespace SolutionErp.Infrastructure.Forms;

public class XlsxRenderer
{
    private static readonly Regex PlaceholderRegex = new(@"\{\{([a-zA-Z0-9_\.]+)\}\}", RegexOptions.Compiled);

    public async Task<RenderResult> RenderAsync(
        string templateAbsolutePath,
        IReadOnlyDictionary<string, string?> data,
        string outputFileName,
        CancellationToken ct = default)
    {
        await Task.Yield();
        using var wb = new XLWorkbook(templateAbsolutePath);

        foreach (var ws in wb.Worksheets)
        {
            foreach (var cell in ws.CellsUsed())
            {
                if (cell.DataType != XLDataType.Text) continue;
                var text = cell.GetString();
                if (!text.Contains("{{")) continue;

                var replaced = PlaceholderRegex.Replace(text, match =>
                {
                    var key = match.Groups[1].Value;
                    return data.TryGetValue(key, out var value) ? (value ?? string.Empty) : match.Value;
                });

                if (replaced != text)
                    cell.Value = replaced;
            }
        }

        using var ms = new MemoryStream();
        wb.SaveAs(ms);

        return new RenderResult(
            ms.ToArray(),
            outputFileName,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }
}
