using ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;

namespace ZB.MOM.WW.ScadaBridge.Commons.Validators;

/// <summary>
/// Pure-function validator for <see cref="OpcUaEndpointConfig"/>. Errors carry
/// the offending property name in <see cref="ValidationEntry.EntityName"/>
/// (optionally prefixed, e.g. "Primary.EndpointUrl") so the form can render
/// per-field messages.
/// </summary>
public static class OpcUaEndpointConfigValidator
{
    /// <summary>
    /// Validates all fields of an <see cref="OpcUaEndpointConfig"/>, returning errors with optionally-prefixed field names.
    /// </summary>
    /// <param name="config">The OPC UA endpoint configuration to validate.</param>
    /// <param name="fieldPrefix">Optional prefix prepended to each field name in error entries (e.g., "Primary.").</param>
    /// <returns>A <see cref="ValidationResult"/> containing field-level errors, or success if all fields are valid.</returns>
    public static ValidationResult Validate(OpcUaEndpointConfig config, string fieldPrefix = "")
    {
        var errors = new List<ValidationEntry>();

        if (string.IsNullOrWhiteSpace(config.EndpointUrl))
            errors.Add(Err("EndpointUrl", "Endpoint URL is required."));
        else if (!Uri.TryCreate(config.EndpointUrl, UriKind.Absolute, out var uri)
                 || uri.Scheme != "opc.tcp"
                 || string.IsNullOrEmpty(uri.Host))
            errors.Add(Err("EndpointUrl", "Endpoint URL must be a valid opc.tcp:// URI."));

        if (config.SessionTimeoutMs <= 0)
            errors.Add(Err("SessionTimeoutMs", "Must be > 0."));
        if (config.OperationTimeoutMs <= 0)
            errors.Add(Err("OperationTimeoutMs", "Must be > 0."));
        if (config.PublishingIntervalMs <= 0)
            errors.Add(Err("PublishingIntervalMs", "Must be > 0."));
        if (config.SamplingIntervalMs <= 0)
            errors.Add(Err("SamplingIntervalMs", "Must be > 0."));
        if (config.QueueSize < 1)
            errors.Add(Err("QueueSize", "Must be ≥ 1."));
        if (config.KeepAliveCount < 1)
            errors.Add(Err("KeepAliveCount", "Must be ≥ 1."));
        if (config.LifetimeCount < config.KeepAliveCount * 3)
            errors.Add(Err("LifetimeCount",
                "Must be at least 3× KeepAliveCount per OPC UA spec."));
        if (config.MaxNotificationsPerPublish < 1)
            errors.Add(Err("MaxNotificationsPerPublish", "Must be ≥ 1."));

        if (string.IsNullOrWhiteSpace(config.SubscriptionDisplayName))
            errors.Add(Err("SubscriptionDisplayName",
                "Subscription display name is required."));

        if (config.Heartbeat is { } hb)
        {
            if (string.IsNullOrWhiteSpace(hb.TagPath))
                errors.Add(Err("Heartbeat.TagPath",
                    "Tag path is required when heartbeat is enabled."));
            if (hb.MaxSilenceSeconds <= 0)
                errors.Add(Err("Heartbeat.MaxSilenceSeconds", "Must be > 0."));
        }

        if (config.UserIdentity is { } ui)
        {
            if (ui.TokenType == OpcUaUserTokenType.UsernamePassword
                && string.IsNullOrWhiteSpace(ui.Username))
                errors.Add(Err("UserIdentity.Username",
                    "Username is required when token type is UsernamePassword."));
            if (ui.TokenType == OpcUaUserTokenType.X509Certificate
                && string.IsNullOrWhiteSpace(ui.CertificatePath))
                errors.Add(Err("UserIdentity.CertificatePath",
                    "Certificate path is required when token type is X509Certificate."));
        }

        if (config.Deadband is { } db && db.Value <= 0)
            errors.Add(Err("Deadband.Value", "Must be > 0."));

        return errors.Count == 0
            ? ValidationResult.Success()
            : ValidationResult.FromErrors(errors.ToArray());

        ValidationEntry Err(string field, string message) =>
            ValidationEntry.Error(
                ValidationCategory.ConnectionConfig,
                message,
                entityName: $"{fieldPrefix}{field}");
    }
}
