using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.InboundApi;

namespace ZB.MOM.WW.ScadaBridge.InboundAPI;

/// <summary>
/// Builds the synchronous JSON-Schema <c>$ref</c> resolution seam the
/// InboundAPI RUNTIME validators (<see cref="ParameterValidator"/> /
/// <see cref="ReturnValueValidator"/>) consume, backed by the central shared-schema
/// library (<see cref="ISharedSchemaRepository"/>).
///
/// <para>
/// Before this fix the runtime validators called the single-arg
/// <c>InboundApiSchema.Parse(json)</c> with NO resolver, so a method whose
/// parameter/return definition used a <c>{"$ref":"lib:Name"}</c> deployed fine
/// (deploy-time validation resolves it) but FAILED at every runtime invocation with
/// an opaque HTTP 400 — a deploy-passes/runtime-breaks defect. This helper mirrors how
/// the deploy path (<c>FlatteningPipeline</c>) pre-loads the library ONCE into an
/// in-memory name→JSON map and exposes a pure synchronous lookup as the seam, avoiding
/// sync-over-async inside the validators.
/// </para>
///
/// <para>
/// The pre-load is gated on <see cref="InboundApiSchema.MightContainRef"/>: a definition
/// that uses no <c>$ref</c> at all skips the repository round-trip entirely and returns
/// <c>null</c> (no resolver), so a <c>$ref</c>-free method pays NO extra cost beyond
/// today's behavior.
/// </para>
/// </summary>
internal static class SchemaRefResolver
{
    /// <summary>
    /// Builds a <c>lib:Name</c> → schema-JSON resolution seam for the supplied
    /// definitions, pre-loading the shared-schema library only when at least one of the
    /// definitions actually contains a <c>$ref</c>.
    /// </summary>
    /// <param name="repository">
    /// The shared-schema repository, or <c>null</c> when none is registered (e.g. a bare
    /// test-double provider) — then no resolver is produced and any <c>$ref</c> dangles.
    /// </param>
    /// <param name="definitions">The schema definition JSON strings to be validated (parameter and/or return).</param>
    /// <param name="ct">Cancellation token for the library load.</param>
    /// <returns>
    /// A synchronous <c>name → schema JSON?</c> resolver, or <c>null</c> when no definition
    /// uses a <c>$ref</c> (so the validators take their unchanged no-resolver path).
    /// </returns>
    public static async Task<Func<string, string?>?> BuildAsync(
        ISharedSchemaRepository? repository,
        IEnumerable<string?> definitions,
        CancellationToken ct = default)
    {
        // Skip the library round-trip entirely unless some definition uses a $ref.
        if (repository is null || !definitions.Any(InboundApiSchema.MightContainRef))
        {
            return null;
        }

        var library = await repository.ListAsync(ct);
        var map = library.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
        return name => map.GetValueOrDefault(name);
    }
}
