using FastEndpoints;
using Shared.Excel;

namespace Modules.Common.Imports.Endpoints;

public sealed record SaveMappingRequest(IReadOnlyList<ImportMapping> Mappings);

public sealed class SaveMappingEndpoint(ImportRepository repository)
    : Endpoint<SaveMappingRequest, ImportSessionDto>
{
    public override void Configure()
    {
        Put("/api/imports/sessions/{sessionId:guid}/mapping");
        Permissions("imports.execute");
    }

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