using ScadaLink.Commons.Types;

namespace ScadaLink.CentralUI.ScriptAnalysis;

/// <summary>
/// Runtime globals for an inbound API method Test Run. Mirrors
/// <see cref="InboundScriptHost"/>'s public surface so the same user code that
/// compiles for diagnostics also compiles against this type — but every
/// <c>Route</c> accessor throws <see cref="ScriptSandboxException"/> instead of
/// reaching a deployed site. Cross-site routing needs the cluster transport and
/// a live instance, neither of which exists in a central Test Run; pure logic
/// and <c>Parameters</c> still work, matching how <see cref="SandboxScriptHost"/>
/// throws on <c>Attributes</c> for shared scripts.
/// </summary>
public class SandboxInboundScriptHost
{
    public ScriptParameters Parameters { get; init; } = new();

    public CancellationToken CancellationToken { get; init; }

    public RouteAccessor Route { get; } = new();

    /// <summary>Mirror of ScadaLink.InboundAPI.RouteHelper.</summary>
    public class RouteAccessor
    {
        public RouteTarget To(string instanceCode) => new(instanceCode);
    }

    /// <summary>Mirror of ScadaLink.InboundAPI.RouteTarget — every call throws.</summary>
    public class RouteTarget
    {
        private readonly string _instanceCode;

        internal RouteTarget(string instanceCode) => _instanceCode = instanceCode;

        public Task<object?> Call(
            string scriptName,
            object? parameters = null,
            CancellationToken cancellationToken = default) =>
            throw Unavailable($"Call(\"{scriptName}\")");

        public Task<object?> GetAttribute(
            string attributeName,
            CancellationToken cancellationToken = default) =>
            throw Unavailable($"GetAttribute(\"{attributeName}\")");

        public Task<IReadOnlyDictionary<string, object?>> GetAttributes(
            IEnumerable<string> attributeNames,
            CancellationToken cancellationToken = default) =>
            throw Unavailable("GetAttributes(...)");

        public Task SetAttribute(
            string attributeName,
            string value,
            CancellationToken cancellationToken = default) =>
            throw Unavailable($"SetAttribute(\"{attributeName}\")");

        public Task SetAttributes(
            IReadOnlyDictionary<string, string> attributeValues,
            CancellationToken cancellationToken = default) =>
            throw Unavailable("SetAttributes(...)");

        private ScriptSandboxException Unavailable(string operation) =>
            new($"Route.To(\"{_instanceCode}\").{operation} is not available in Test Run — " +
                "cross-site routing needs a deployed site reachable over the cluster transport.");
    }
}
