using System.Text.Json;
using Tiku.Application.Content;
using Tiku.Application.Jobs;
using Tiku.Infrastructure.Jobs;

namespace Tiku.Infrastructure.Content.Imports;

internal sealed class ContentImportJobHandler(IDirectContentService directContentService) : IBackgroundJobHandler
{
    public string JobType => "content_import";

    public async Task<BackgroundJobHandlerResult> HandleAsync(
        BackgroundJobExecutionContext context,
        CancellationToken cancellationToken = default)
    {
        var createdBy = BackgroundJobPayload.GetGuid(context.Payload, "createdBy") ?? Guid.Empty;
        if (createdBy == Guid.Empty) throw new InvalidOperationException("content_import job requires createdBy.");

        var command = new SimpleImportCommand(
            BackgroundJobPayload.GetString(context.Payload, "importType") ??
            throw new InvalidOperationException("content_import job requires importType."),
            BackgroundJobPayload.GetString(context.Payload, "sourceFormat"),
            BackgroundJobPayload.GetString(context.Payload, "sourceName"),
            BackgroundJobPayload.GetGuid(context.Payload, "regionId"),
            BackgroundJobPayload.GetGuid(context.Payload, "entryId"),
            BackgroundJobPayload.GetGuid(context.Payload, "contentNodeId"),
            BackgroundJobPayload.GetGuid(context.Payload, "subjectId"),
            BackgroundJobPayload.GetGuid(context.Payload, "categoryId"),
            BackgroundJobPayload.GetGuid(context.Payload, "questionBankId"),
            BackgroundJobPayload.GetGuid(context.Payload, "collectionId"),
            BackgroundJobPayload.GetArray(context.Payload, "items"),
            false);
        var result = await directContentService.ExecuteImportAsync(
            new DirectContentActor(context.TenantId, createdBy),
            command,
            cancellationToken);
        return new BackgroundJobHandlerResult(JsonSerializer.SerializeToElement(new
        {
            importJobId = result.Job.Id,
            result.Job.ImportType,
            result.Job.Status,
            result.Job.TotalCount,
            result.Job.InsertedCount,
            result.Job.UpdatedCount,
            result.Job.ErrorCount
        }));
    }
}
