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

namespace Modules.Common.Imports.Endpoints;

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

    public override async Task HandleAsync(CancellationToken ct)
    {
        var id = Route<Guid>("sessionId");
        var tenant = ImportIdentity.TenantId(User);
        var actor = ImportIdentity.UserId(User);
        var session = await repository.GetAsync(id, tenant, actor, false, ct);
        if (session is null) { await Send.NotFoundAsync(ct); return; }
        if (session.Status != ImportStatuses.Validated)
        {
            AddError("검증 완료된 Import만 반영할 수 있습니다.");
            await Send.ErrorsAsync(cancellation: ct);
            return;
        }
        var acquired = await repository.TryTransitionAsync(id, [ImportStatuses.Validated], ImportStatuses.Committing, 1, ct);
        if (acquired)
        {
            try { jobs.Enqueue<CommitImportJob>(job => job.RunAsync(id, actor, CancellationToken.None)); }
            catch { await repository.SetStatusAsync(id, ImportStatuses.Validated, 100, ct); throw; }
        }
        var current = await repository.GetAsync(id, tenant, actor, false, ct);
        await Send.OkAsync(current!, ct);
    }
}
