namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;

public enum TemplateTreeNodeKind
{
    Folder,
    Template,

    /// <summary>
    /// Composition slot under a parent Template — produced only by callers that
    /// supply <c>TemplateFolderTree.ExtraTemplateChildren</c>. The Transport
    /// Export wizard intentionally never emits this kind (compositions aren't
    /// independently exportable); the Templates page uses it to surface slots.
    /// </summary>
    Composition,
}

/// <summary>
/// Adapter node used by <c>TemplateFolderTree</c> to model the template-folder
/// hierarchy in a TreeView. Folder nodes carry sub-folders + their templates as
/// children; template nodes are leaves unless the caller injects extras via
/// <c>TemplateFolderTree.ExtraTemplateChildren</c> (e.g. composition slots).
/// </summary>
public sealed class TemplateTreeNode
{
    /// <summary>Discriminator indicating whether this node represents a folder, template, or composition slot.</summary>
    public required TemplateTreeNodeKind Kind { get; init; }
    /// <summary>Database id of the underlying folder, template, or composition record.</summary>
    public required int Id { get; init; }
    /// <summary>Display name of the node.</summary>
    public required string Name { get; init; }
    /// <summary>Child nodes (sub-folders, templates, or composition slots).</summary>
    public List<TemplateTreeNode> Children { get; } = new();

    /// <summary>
    /// True when this composition node is <em>inherited</em> — its underlying
    /// <c>TemplateComposition</c> row belongs to an ancestor of the template it is
    /// rendered under, not to that template itself. Inherited nodes are
    /// badged read-only and their context menu suppresses Rename/Delete (those edit the
    /// base). Always false for folders and templates.
    /// </summary>
    public bool IsInherited { get; init; }

    /// <summary>
    /// Explicit, path-qualified key override. The same inherited composition row can
    /// surface under several derived members (e.g. LeakTest under both LeftReactorSide
    /// and RightReactorSide), so a plain <c>c:{Id}</c> key would collide and break the
    /// TreeView's selection/expansion tracking. Composition nodes set this to a
    /// parent-path-qualified value; folders/templates leave it null and use the default.
    /// </summary>
    public string? KeyOverride { get; init; }

    /// <summary>Stable key for TreeView selection / expansion tracking.</summary>
    public string Key => KeyOverride ?? Kind switch
    {
        TemplateTreeNodeKind.Folder => $"f:{Id}",
        TemplateTreeNodeKind.Template => $"t:{Id}",
        TemplateTreeNodeKind.Composition => $"c:{Id}",
        _ => $"x:{Id}",
    };
}
