namespace ScadaLink.Commons.Types.Flattening;

/// <summary>
/// Result of pre-deployment or on-demand validation with categorized errors and warnings.
/// </summary>
public sealed record ValidationResult
{
    public bool IsValid => Errors.Count == 0;
    public IReadOnlyList<ValidationEntry> Errors { get; init; } = [];
    public IReadOnlyList<ValidationEntry> Warnings { get; init; } = [];

    public static ValidationResult Success() => new();

    public static ValidationResult FromErrors(params ValidationEntry[] errors) =>
        new() { Errors = errors };

    public static ValidationResult Merge(params ValidationResult[] results)
    {
        var errors = new List<ValidationEntry>();
        var warnings = new List<ValidationEntry>();
        foreach (var r in results)
        {
            errors.AddRange(r.Errors);
            warnings.AddRange(r.Warnings);
        }
        return new ValidationResult { Errors = errors, Warnings = warnings };
    }
}

/// <summary>
/// A single validation error or warning with category and context.
/// </summary>
public sealed record ValidationEntry
{
    public ValidationCategory Category { get; init; }
    public string Message { get; init; } = string.Empty;

    /// <summary>
    /// The canonical name of the entity that caused the validation issue, if applicable.
    /// </summary>
    public string? EntityName { get; init; }

    public static ValidationEntry Error(ValidationCategory category, string message, string? entityName = null) =>
        new() { Category = category, Message = message, EntityName = entityName };

    public static ValidationEntry Warning(ValidationCategory category, string message, string? entityName = null) =>
        new() { Category = category, Message = message, EntityName = entityName };
}

public enum ValidationCategory
{
    FlatteningFailure,
    NamingCollision,
    ScriptCompilation,
    AlarmTriggerReference,
    ScriptTriggerReference,
    ConnectionBinding,
    CallTargetNotFound,
    ParameterMismatch,
    ReturnTypeMismatch,
    TriggerOperandType,
    OnTriggerScriptNotFound,
    CrossCallViolation,
    MissingMetadata,
    ConnectionConfig
}
