using FastEndpoints;
using Hangfire;
using Modules.Common.Imports.Jobs;
using Shared.Excel;

namespace Modules.Common.Imports.Endpoints;

public sealed class ValidateEndpoint(ImportRepository repository, IBackgroundJobClient jobs)
    : EndpointWithoutRequest<ImportSessionDto>
{
    public override void Configure()
    {
        Post("/api/imports/sessions/{sessionId:guid}/validate");
        Permissions("imports.execute");
    }

    public override async Task HandleAsync(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; }

        var acquired = await repository.TryTransitionAsync(id,
            [ImportStatuses.MappingRequired, ImportStatuses.Uploaded, ImportStatuses.Failed],
            ImportStatuses.Validating, 1, ct);
        if (acquired)
        {
            try { jobs.Enqueue<ValidateImportJob>(job => job.RunAsync(id, CancellationToken.None)); }
            catch { await repository.SetStatusAsync(id, ImportStatuses.MappingRequired, 0, ct); throw; }
        }
        var current = await repository.GetAsync(id, tenant, user, false, ct);
        await Send.OkAsync(current!, ct);
    }
}
