using FastEndpoints;
using Shared.Excel;

namespace Modules.Common.Imports.Endpoints;

public sealed class TemplateEndpoint(ImportDefinitionRegistry registry, ClosedXmlWorkbookService workbook)
    : EndpointWithoutRequest
{
    public override void Configure()
    {
        Get("/api/imports/{importType}/template");
        Permissions("imports.execute");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        var importType = Route<string>("importType")!;
        if (!registry.TryGet(importType, out var definition) || definition is null) { await Send.NotFoundAsync(ct); return; }
        var stream = workbook.CreateTemplate(definition.Definition);
        await Send.StreamAsync(stream,
            fileName: $"{definition.Definition.Entity}_import_template.xlsx",
            fileLengthBytes: stream.Length,
            contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            cancellation: ct);
    }
}
