using System.Collections.Generic;
using Microsoft.Extensions.Options;

namespace StellaOps.Excititor.Worker.Options;

internal sealed class VexWorkerOptionsValidator : IValidateOptions<VexWorkerOptions>
{
    public ValidateOptionsResult Validate(string? name, VexWorkerOptions options)
    {
        var failures = new List<string>();

        if (options.DefaultInterval <= TimeSpan.Zero)
        {
            failures.Add("Excititor.Worker.DefaultInterval must be greater than zero.");
        }

        if (options.OfflineInterval <= TimeSpan.Zero)
        {
            failures.Add("Excititor.Worker.OfflineInterval must be greater than zero.");
        }

        if (options.DefaultInitialDelay < TimeSpan.Zero)
        {
            failures.Add("Excititor.Worker.DefaultInitialDelay cannot be negative.");
        }

        for (var i = 0; i < options.Providers.Count; i++)
        {
            var provider = options.Providers[i];
            if (string.IsNullOrWhiteSpace(provider.ProviderId))
            {
                failures.Add($"Excititor.Worker.Providers[{i}].ProviderId must be set.");
            }

            if (provider.Interval is { } interval && interval <= TimeSpan.Zero)
            {
                failures.Add($"Excititor.Worker.Providers[{i}].Interval must be greater than zero when specified.");
            }

            if (provider.InitialDelay is { } delay && delay < TimeSpan.Zero)
            {
                failures.Add($"Excititor.Worker.Providers[{i}].InitialDelay cannot be negative.");
            }
        }

        return failures.Count > 0
            ? ValidateOptionsResult.Fail(failures)
            : ValidateOptionsResult.Success;
    }
}
