using FastEndpoints;
using Shared.Excel;

namespace Modules.Common.Imports.Endpoints;

public sealed record SaveNamedMappingRequest(string Name, IReadOnlyList<ImportMapping> Mappings);

public sealed class SaveNamedMappingEndpoint(ImportRepository repository)
    : Endpoint<SaveNamedMappingRequest>
{
    public override void Configure()
    {
        Post("/api/imports/sessions/{sessionId:guid}/saved-mappings");
        Permissions("imports.execute");
    }

    public override async Task HandleAsync(SaveNamedMappingRequest req, CancellationToken ct)
    {
        var id = Route<Guid>("sessionId");
        var tenant = ImportIdentity.TenantId(User);
        var user = ImportIdentity.UserId(User);
        var session = await repository.GetAsync(id, tenant, user, false, ct);
        if (session is null) { await Send.NotFoundAsync(ct); return; }
        await repository.SaveNamedMappingAsync(tenant, user, session.ImportType, req.Name, session.SourceColumns, req.Mappings, ct);
        await Send.NoContentAsync(ct);
    }
}
