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="MxGatewayEndpointConfig"/>. Errors carry
/// the offending property name in <see cref="ValidationEntry.EntityName"/>
/// (optionally prefixed, e.g. "Primary.Endpoint") so the form can render
/// per-field messages.
/// </summary>
public static class MxGatewayEndpointConfigValidator
{
    /// <summary>
    /// Validates all fields of an <see cref="MxGatewayEndpointConfig"/>, returning errors with optionally-prefixed field names.
    /// </summary>
    /// <param name="config">The MxGateway 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"/> with errors for any invalid fields, or a success result when all fields are valid.</returns>
    public static ValidationResult Validate(MxGatewayEndpointConfig config, string fieldPrefix = "")
    {
        var errors = new List<ValidationEntry>();

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

        if (string.IsNullOrWhiteSpace(config.ApiKey))
            errors.Add(Err("ApiKey", "API key is required."));

        if (config.ReadTimeoutMs <= 0)
            errors.Add(Err("ReadTimeoutMs", "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}");
    }
}
