using System.Diagnostics.CodeAnalysis;

namespace StellaOps.Feedser.Source.Jvn.Configuration;

/// <summary>
/// Options controlling the JVN connector fetch cadence and HTTP client configuration.
/// </summary>
public sealed class JvnOptions
{
    public static string HttpClientName => "source.jvn";

    /// <summary>
    /// Base endpoint for the MyJVN API.
    /// </summary>
    public Uri BaseEndpoint { get; set; } = new("https://jvndb.jvn.jp/myjvn", UriKind.Absolute);

    /// <summary>
    /// Size of each fetch window applied to dateFirstPublished/dateLastUpdated queries.
    /// </summary>
    public TimeSpan WindowSize { get; set; } = TimeSpan.FromDays(7);

    /// <summary>
    /// Overlap applied between consecutive windows to ensure late-arriving updates are captured.
    /// </summary>
    public TimeSpan WindowOverlap { get; set; } = TimeSpan.FromDays(1);

    /// <summary>
    /// Number of overview records requested per page (MyJVN max is 50).
    /// </summary>
    public int PageSize { get; set; } = 50;

    /// <summary>
    /// Optional delay enforced between HTTP requests to respect service rate limits.
    /// </summary>
    public TimeSpan RequestDelay { get; set; } = TimeSpan.FromMilliseconds(500);

    /// <summary>
    /// Maximum number of overview pages the connector will request in a single fetch cycle.
    /// </summary>
    public int MaxOverviewPagesPerFetch { get; set; } = 20;

    [MemberNotNull(nameof(BaseEndpoint))]
    public void Validate()
    {
        if (BaseEndpoint is null || !BaseEndpoint.IsAbsoluteUri)
        {
            throw new InvalidOperationException("JVN options require an absolute BaseEndpoint.");
        }

        if (WindowSize <= TimeSpan.Zero)
        {
            throw new InvalidOperationException("WindowSize must be greater than zero.");
        }

        if (WindowOverlap < TimeSpan.Zero)
        {
            throw new InvalidOperationException("WindowOverlap cannot be negative.");
        }

        if (WindowOverlap >= WindowSize)
        {
            throw new InvalidOperationException("WindowOverlap must be smaller than WindowSize.");
        }

        if (PageSize is < 1 or > 50)
        {
            throw new InvalidOperationException("PageSize must be between 1 and 50 to satisfy MyJVN limits.");
        }

        if (RequestDelay < TimeSpan.Zero)
        {
            throw new InvalidOperationException("RequestDelay cannot be negative.");
        }

        if (MaxOverviewPagesPerFetch <= 0)
        {
            throw new InvalidOperationException("MaxOverviewPagesPerFetch must be positive.");
        }
    }
}
