package alwaysaccept

import (
	"context"

	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
)

const Key = "generic/always_accept"

type Options struct{}
type ChunkValidator struct{}
type TypedValidator[T any] struct{}

var _ contracts.ChunkValidator = (*ChunkValidator)(nil)

func NewChunk(Options) *ChunkValidator           { return &ChunkValidator{} }
func NewTyped[T any](Options) *TypedValidator[T] { return &TypedValidator[T]{} }

func (v *ChunkValidator) Name() string { return Key }
func (v *ChunkValidator) ExecutionClass() contracts.ExecutionClass {
	return contracts.ExecutionClassDeterministic
}
func (v *ChunkValidator) Validate(context.Context, contracts.ChunkValidationRequest) (contracts.ValidationResult, error) {
	return contracts.ValidationResult{Approved: true}, nil
}

func (v *TypedValidator[T]) Name() string { return Key }
func (v *TypedValidator[T]) ExecutionClass() contracts.ExecutionClass {
	return contracts.ExecutionClassDeterministic
}
func (v *TypedValidator[T]) Validate(context.Context, contracts.TypedValidationRequest[T]) (contracts.ValidationResult, error) {
	return contracts.ValidationResult{Approved: true}, nil
}

func Spec() pipeline.ValidatorSpec {
	return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
}

func Register(registry *pipeline.ValidatorRegistry) error {
	return pipeline.RegisterChunkValidatorBuilder(registry, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.ChunkValidator, error) {
		options, err := DecodeOptions(request.Options)
		if err != nil {
			return nil, err
		}
		return NewChunk(options), nil
	})
}

func RegisterTyped[T any](registry *pipeline.ValidatorRegistry, kind contracts.ArtifactKind) error {
	return pipeline.RegisterTypedValidatorBuilder(registry, kind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[T], error) {
		options, err := DecodeOptions(request.Options)
		if err != nil {
			return nil, err
		}
		return NewTyped[T](options), nil
	})
}

func DecodeOptions(options map[string]any) (Options, error) {
	if err := pipeline.RejectUnknownOptions(options); err != nil {
		return Options{}, err
	}
	return Options{}, nil
}
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
