using ZB.MOM.WW.ScadaBridge.TemplateEngine;

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

/// <summary>
/// Indirection so ScriptAnalysisService can be unit-tested without standing
/// up SharedScriptService and its EF Core repository chain.
/// </summary>
public interface ISharedScriptCatalog
{
    /// <summary>Returns the parameter and return shapes for all registered shared scripts.</summary>
    /// <returns>A task that resolves to the list of all shared script shapes.</returns>
    Task<IReadOnlyList<ScriptShape>> GetShapesAsync();

    /// <summary>
    /// Returns the source code and metadata for a named shared script, or
    /// null if no shared script with that name exists. Used by Test Run to
    /// compile and execute nested CallShared invocations.
    /// </summary>
    /// <param name="name">Name of the shared script to retrieve.</param>
    /// <param name="cancellationToken">Cancellation token for the async lookup.</param>
    /// <returns>A task that resolves to the matching shared script source, or null if none exists.</returns>
    Task<SharedScriptSource?> GetByNameAsync(string name, CancellationToken cancellationToken = default);
}

public record SharedScriptSource(string Name, string Code, string? ParameterDefinitions, string? ReturnDefinition);

public class SharedScriptCatalog : ISharedScriptCatalog
{
    private readonly SharedScriptService _service;

    /// <summary>
    /// Initializes a new <see cref="SharedScriptCatalog"/> backed by the given service.
    /// </summary>
    /// <param name="service">Service providing access to shared script definitions.</param>
    public SharedScriptCatalog(SharedScriptService service) => _service = service;

    /// <inheritdoc />
    public async Task<IReadOnlyList<ScriptShape>> GetShapesAsync()
    {
        var scripts = await _service.GetAllSharedScriptsAsync();
        return scripts
            .Select(s => ScriptShapeParser.Parse(s.Name, s.ParameterDefinitions, s.ReturnDefinition))
            .ToList();
    }

    /// <inheritdoc />
    public async Task<SharedScriptSource?> GetByNameAsync(string name, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrEmpty(name)) return null;
        var scripts = await _service.GetAllSharedScriptsAsync(cancellationToken);
        var s = scripts.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.Ordinal));
        return s == null ? null : new SharedScriptSource(s.Name, s.Code, s.ParameterDefinitions, s.ReturnDefinition);
    }
}
