using Shared.Excel;

namespace Modules.Common.Imports.Jobs;

public sealed class CommitImportJob(
    ImportRepository repository,
    ImportDefinitionRegistry registry,
    ImportProgressPublisher progress)
{
    public async Task RunAsync(Guid sessionId, string actor, CancellationToken ct)
    {
        try
        {
            var (importType, _) = await repository.GetWorkDefinitionAsync(sessionId, ct);
            var definition = registry.Get(importType);
            await progress.PublishAsync(new ImportProgressEvent(
                sessionId, ImportStatuses.Committing, 1, 0, 0, 0, 0, 0,
                "검증된 데이터를 반영하고 있습니다."), ct);

            var result = await definition.CommitAsync(sessionId, actor, ct);
            await repository.CompleteAsync(sessionId, result, ct);
            await progress.PublishAsync(new ImportProgressEvent(
                sessionId,
                result.Failed > 0 ? ImportStatuses.PartiallyCompleted : ImportStatuses.Completed,
                100,
                result.Created + result.Updated + result.Failed,
                result.Created + result.Updated + result.Failed,
                result.Created + result.Updated,
                result.Failed,
                0,
                result.Failed > 0 ? "일부 데이터가 오류로 제외되었습니다." : "반영이 완료되었습니다."), ct);
        }
        catch (Exception)
        {
            await repository.SetStatusAsync(sessionId, ImportStatuses.Failed, 100, ct);
            throw;
        }
    }
}
