using System.Data.Common;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Notification;

namespace ZB.MOM.WW.ScadaBridge.CentralUI.ScriptAnalysis;

/// <summary>
/// User-facing surface for <c>ExternalSystem.Call</c> /
/// <c>ExternalSystem.CachedCall</c> inside a Test Run. Mirrors
/// ExternalSystemHelper in ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts.ScriptRuntimeContext
/// so the same user code compiles against both. When constructed with a null
/// client (the editor's metadata-only analysis pass) every call throws
/// <see cref="ScriptSandboxException"/>; with a real client wired in (a Test
/// Run) calls hit the live HTTP path.
/// </summary>
public class SandboxExternalHelper
{
    private readonly IExternalSystemClient? _client;
    private readonly string _instanceName;

    /// <summary>Initializes a new instance of the SandboxExternalHelper class.</summary>
    /// <param name="client">Optional external system client for test runs.</param>
    /// <param name="instanceName">The instance name context.</param>
    public SandboxExternalHelper(IExternalSystemClient? client, string instanceName)
    {
        _client = client;
        _instanceName = instanceName;
    }

    /// <summary>Invokes a synchronous external system call.</summary>
    /// <param name="systemName">The external system name.</param>
    /// <param name="methodName">The method name to invoke.</param>
    /// <param name="parameters">Optional method parameters.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that resolves to the <see cref="ExternalCallResult"/> from the external system.</returns>
    public Task<ExternalCallResult> Call(
        string systemName,
        string methodName,
        IReadOnlyDictionary<string, object?>? parameters = null,
        CancellationToken cancellationToken = default)
    {
        if (_client == null)
            throw new ScriptSandboxException(
                $"External.Call(\"{systemName}\", \"{methodName}\") — external system client not configured for Test Run.");
        return _client.CallAsync(systemName, methodName, parameters, cancellationToken);
    }

    /// <summary>Invokes a cached external system call.</summary>
    /// <param name="systemName">The external system name.</param>
    /// <param name="methodName">The method name to invoke.</param>
    /// <param name="parameters">Optional method parameters.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that resolves to the <see cref="ExternalCallResult"/> from the external system.</returns>
    public Task<ExternalCallResult> CachedCall(
        string systemName,
        string methodName,
        IReadOnlyDictionary<string, object?>? parameters = null,
        CancellationToken cancellationToken = default)
    {
        if (_client == null)
            throw new ScriptSandboxException(
                $"External.CachedCall(\"{systemName}\", \"{methodName}\") — external system client not configured for Test Run.");
        return _client.CachedCallAsync(systemName, methodName, parameters, _instanceName, cancellationToken);
    }
}

/// <summary>Sandbox database helper for script analysis.</summary>
public class SandboxDatabaseHelper
{
    private readonly IDatabaseGateway? _gateway;
    private readonly string _instanceName;

    /// <summary>Initializes a new instance of the SandboxDatabaseHelper class.</summary>
    /// <param name="gateway">Optional database gateway for test runs.</param>
    /// <param name="instanceName">The instance name context.</param>
    public SandboxDatabaseHelper(IDatabaseGateway? gateway, string instanceName)
    {
        _gateway = gateway;
        _instanceName = instanceName;
    }

    /// <summary>Gets a database connection by name.</summary>
    /// <param name="name">The database connection name.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that resolves to the open <see cref="DbConnection"/> for the named database.</returns>
    public Task<DbConnection> Connection(string name, CancellationToken cancellationToken = default)
    {
        if (_gateway == null)
            throw new ScriptSandboxException(
                $"Database.Connection(\"{name}\") — database gateway not configured for Test Run.");
        return _gateway.GetConnectionAsync(name, cancellationToken);
    }

    /// <summary>Executes a cached database write operation.</summary>
    /// <param name="name">The database connection name.</param>
    /// <param name="sql">The SQL statement to execute.</param>
    /// <param name="parameters">Optional SQL parameters.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    public Task CachedWrite(
        string name,
        string sql,
        IReadOnlyDictionary<string, object?>? parameters = null,
        CancellationToken cancellationToken = default)
    {
        if (_gateway == null)
            throw new ScriptSandboxException(
                $"Database.CachedWrite(\"{name}\") — database gateway not configured for Test Run.");
        return _gateway.CachedWriteAsync(name, sql, parameters, _instanceName, cancellationToken);
    }
}

/// <summary>
/// Sandbox mirror of <c>ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts.NotifyHelper</c> — the
/// <c>Notify</c> global. Signature-faithful to production so the same user code
/// (<c>Notify.To(...).Send(...)</c> / <c>Notify.Status(...)</c>) compiles
/// identically against both surfaces.
///
/// In the Notification Outbox design production no longer delivers notification
/// email inline — <c>Notify.Send</c> enqueues into the site Store-and-Forward
/// Engine and returns a <c>NotificationId</c>. The sandbox has no S&amp;F engine
/// and no central, so it is a pure no-op fake: <c>Send</c> returns a generated
/// fake id and <c>Status</c> returns a placeholder <see cref="NotificationDeliveryStatus"/>.
/// Nothing is delivered.
/// </summary>
public class SandboxNotifyHelper
{
    /// <summary>Selects the notification list to send to.</summary>
    /// <param name="listName">The notification list name.</param>
    /// <returns>A <see cref="SandboxNotifyTarget"/> for the specified list.</returns>
    public SandboxNotifyTarget To(string listName) =>
        new();

    /// <summary>
    /// Queries the delivery status of a previously-sent notification. The
    /// sandbox never delivers, so this always reports the placeholder
    /// <c>Unknown</c> status — it exists for signature fidelity with
    /// <c>NotifyHelper.Status</c>.
    /// </summary>
    /// <param name="notificationId">The notification ID to check status for.</param>
    /// <returns>A task that resolves to a placeholder <see cref="NotificationDeliveryStatus"/> with status "Unknown".</returns>
    public Task<NotificationDeliveryStatus> Status(string notificationId) =>
        Task.FromResult(new NotificationDeliveryStatus("Unknown", 0, null, null));
}

/// <summary>
/// Sandbox mirror of <c>ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts.NotifyTarget</c> — the
/// target of <c>Notify.To("listName")</c>.
/// </summary>
public class SandboxNotifyTarget
{
    /// <summary>Initializes a new instance of the SandboxNotifyTarget class.</summary>
    internal SandboxNotifyTarget()
    {
    }

    /// <summary>
    /// Mirrors <c>NotifyTarget.Send</c> — returns a <c>NotificationId</c>. In
    /// the sandbox nothing is enqueued or delivered; a fake id is returned so
    /// the call type-checks identically to production.
    /// </summary>
    /// <param name="subject">The notification subject.</param>
    /// <param name="message">The notification message.</param>
    /// <param name="cancellationToken">Cancellation token.</param>
    /// <returns>A task that resolves to a fake notification ID string (a random GUID).</returns>
    public Task<string> Send(string subject, string message, CancellationToken cancellationToken = default) =>
        Task.FromResult(Guid.NewGuid().ToString("N"));
}
