// Copyright 2022-2026 Princess Beef Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT

package arazzo

import (
	"context"
	"hash/maphash"

	"github.com/pb33f/libopenapi/datamodel/low"
	"github.com/pb33f/libopenapi/index"
	"github.com/pb33f/libopenapi/orderedmap"
	"go.yaml.in/yaml/v4"
)

// SuccessAction represents a low-level Arazzo Success Action Object.
// A success action can be a full definition or a Reusable Object with a $components reference.
// https://spec.openapis.org/arazzo/v1.0.1#success-action-object
type SuccessAction struct {
	Name       low.NodeReference[string]
	Type       low.NodeReference[string]
	WorkflowId low.NodeReference[string]
	StepId     low.NodeReference[string]
	Criteria   low.NodeReference[[]low.ValueReference[*Criterion]]
	ComponentRef low.NodeReference[string]
	Extensions *orderedmap.Map[low.KeyReference[string], low.ValueReference[*yaml.Node]]
	KeyNode    *yaml.Node
	RootNode   *yaml.Node
	index      *index.SpecIndex
	context    context.Context
	*low.Reference
	low.NodeMap
}

var extractSuccessActionCriteria = extractArray[Criterion]

// IsReusable returns true if this success action is a Reusable Object (has a reference field).
func (s *SuccessAction) IsReusable() bool {
	return !s.ComponentRef.IsEmpty()
}

// GetIndex returns the index.SpecIndex instance attached to the SuccessAction object.
// For Arazzo low models this is typically nil, because Arazzo parsing does not build a SpecIndex.
// The index parameter is still required to satisfy the shared low.Buildable interface and generic extractors.
func (s *SuccessAction) GetIndex() *index.SpecIndex {
	return s.index
}

// GetContext returns the context.Context instance used when building the SuccessAction object.
func (s *SuccessAction) GetContext() context.Context {
	return s.context
}

// FindExtension returns a ValueReference containing the extension value, if found.
func (s *SuccessAction) FindExtension(ext string) *low.ValueReference[*yaml.Node] {
	return low.FindItemInOrderedMap(ext, s.Extensions)
}

// GetRootNode returns the root yaml node of the SuccessAction object.
func (s *SuccessAction) GetRootNode() *yaml.Node {
	return s.RootNode
}

// GetKeyNode returns the key yaml node of the SuccessAction object.
func (s *SuccessAction) GetKeyNode() *yaml.Node {
	return s.KeyNode
}

// Build will extract all properties of the SuccessAction object.
func (s *SuccessAction) Build(ctx context.Context, keyNode, root *yaml.Node, idx *index.SpecIndex) error {
	root = initBuild(&arazzoBase{
		KeyNode:    &s.KeyNode,
		RootNode:   &s.RootNode,
		Reference:  &s.Reference,
		NodeMap:    &s.NodeMap,
		Extensions: &s.Extensions,
		Index:      &s.index,
		Context:    &s.context,
	}, ctx, keyNode, root, idx)

	s.ComponentRef = extractComponentRef(ReferenceLabel, root)

	// Extract criteria array
	criteria, err := extractSuccessActionCriteria(ctx, CriteriaLabel, root, idx)
	if err != nil {
		return err
	}
	s.Criteria = criteria
	return nil
}

// GetExtensions returns all SuccessAction extensions and satisfies the low.HasExtensions interface.
func (s *SuccessAction) GetExtensions() *orderedmap.Map[low.KeyReference[string], low.ValueReference[*yaml.Node]] {
	return s.Extensions
}

// Hash will return a consistent hash of the SuccessAction object.
func (s *SuccessAction) Hash() uint64 {
	return low.WithHasher(func(h *maphash.Hash) uint64 {
		if !s.ComponentRef.IsEmpty() {
			h.WriteString(s.ComponentRef.Value)
			h.WriteByte(low.HASH_PIPE)
		}
		if !s.Name.IsEmpty() {
			h.WriteString(s.Name.Value)
			h.WriteByte(low.HASH_PIPE)
		}
		if !s.Type.IsEmpty() {
			h.WriteString(s.Type.Value)
			h.WriteByte(low.HASH_PIPE)
		}
		if !s.WorkflowId.IsEmpty() {
			h.WriteString(s.WorkflowId.Value)
			h.WriteByte(low.HASH_PIPE)
		}
		if !s.StepId.IsEmpty() {
			h.WriteString(s.StepId.Value)
			h.WriteByte(low.HASH_PIPE)
		}
		if !s.Criteria.IsEmpty() {
			for _, c := range s.Criteria.Value {
				low.HashUint64(h, c.Value.Hash())
			}
		}
		hashExtensionsInto(h, s.Extensions)
		return h.Sum64()
	})
}
