using System.Text.Json;
using Tiku.Application.Jobs;
using Tiku.Application.Security;
using Tiku.Domain.Operations;

namespace Tiku.Infrastructure.Jobs;

internal sealed partial class BackgroundJobService
{
    private static string NormalizeJobType(string jobType)
    {
        return jobType.Trim().ToLowerInvariant();
    }

    private static string? NormalizeIdempotencyKey(string? value)
    {
        var normalized = value?.Trim();
        if (string.IsNullOrEmpty(normalized)) return null;
        if (normalized.Length > 200)
            throw new BackgroundJobException("background_job_idempotency_key_too_long",
                "Idempotency key cannot exceed 200 characters.");
        return normalized;
    }

    private static string ResolveRequiredFeature(string jobType, JsonElement payload)
    {
        return jobType switch
        {
            "content_import" => SaasFeatureCatalog.ResolveContentImportFeature(GetJsonString(payload, "importType"))
                                ?? throw new InvalidOperationException(
                                    "Background content import type is not supported."),
            "content_export" or "asset_security_scan" => SaasFeatureCatalog.PrivateQuestionBank,
            "commerce_reconciliation" => SaasFeatureCatalog.StudentStore,
            "statistics_aggregation" or "tenant_domain_recheck" => SaasFeatureCatalog.CoreBackoffice,
            _ => SaasFeatureCatalog.CoreBackoffice
        };
    }

    private static string? GetJsonString(JsonElement element, string propertyName)
    {
        return element.ValueKind == JsonValueKind.Object &&
               element.TryGetProperty(propertyName, out var property) &&
               property.ValueKind == JsonValueKind.String
            ? property.GetString()
            : null;
    }

    private static BackgroundJobItem ToItem(BackgroundJob job)
    {
        return new BackgroundJobItem(
            job.Id,
            job.TenantId,
            job.JobType,
            job.IdempotencyKey,
            job.Status,
            job.RetryCount,
            job.MaxRetries,
            job.RunAfter,
            job.StartedAt,
            job.CompletedAt,
            job.CancellationRequestedAt,
            job.CancellationRequestedBy,
            job.CancellationReason,
            job.LastError,
            job.OutputAssetId,
            job.Result);
    }
}
