using FastEndpoints;
using Shared.Excel;

namespace Modules.Common.Imports.Endpoints;

public sealed class ErrorWorkbookEndpoint(ImportRepository repository, ClosedXmlWorkbookService workbook)
    : EndpointWithoutRequest
{
    public override void Configure()
    {
        Get("/api/imports/sessions/{sessionId:guid}/errors.xlsx");
        Permissions("imports.execute");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        var id = Route<Guid>("sessionId");
        var session = await repository.GetAsync(id, ImportIdentity.TenantId(User), ImportIdentity.UserId(User), false, ct);
        if (session is null) { await Send.NotFoundAsync(ct); return; }
        var (_, bytes) = await repository.GetFileAsync(id, ct);
        await using var source = new MemoryStream(bytes, writable: false);
        var errors = await repository.GetErrorsAsync(id, ct);
        var output = workbook.CreateErrorWorkbook(source, errors);
        await Send.StreamAsync(output,
            fileName: $"{Path.GetFileNameWithoutExtension(session.FileName)}_errors.xlsx",
            fileLengthBytes: output.Length,
            contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            cancellation: ct);
    }
}
