using System.Text.Json;
using Tiku.Domain.Operations;

namespace Tiku.Application.Jobs;

public sealed record CreateBackgroundJobCommand(
    Guid TenantId,
    string JobType,
    JsonElement Payload,
    DateTimeOffset? RunAfter = null,
    int MaxRetries = 3);

public sealed record BackgroundJobItem(
    Guid Id,
    Guid TenantId,
    string JobType,
    BackgroundJobStatus Status,
    int RetryCount,
    int MaxRetries,
    DateTimeOffset? RunAfter,
    DateTimeOffset? StartedAt,
    DateTimeOffset? CompletedAt,
    string? LastError,
    Guid? OutputAssetId,
    JsonElement Result);

public interface IBackgroundJobService
{
    Task<BackgroundJobItem> EnqueueAsync(
        CreateBackgroundJobCommand command,
        CancellationToken cancellationToken = default);

    Task<int> ProcessPendingAsync(
        string workerId,
        int batchSize,
        bool includeImmediateJobs = true,
        CancellationToken cancellationToken = default);

    Task<bool> ProcessRequestedAsync(
        Guid jobId,
        Guid tenantId,
        string jobType,
        string workerId,
        CancellationToken cancellationToken = default);

    Task<IReadOnlyCollection<BackgroundJobItem>> ListAsync(
        Guid tenantId,
        string? jobType = null,
        int limit = 50,
        CancellationToken cancellationToken = default);
}
