package processor

import (
	"context"
	"errors"
	"fmt"
	"log/slog"

	"github.com/google/jsonschema-go/jsonschema"
	"github.com/jwetzell/showbridge-go/config"
	"github.com/jwetzell/showbridge-go/internal/common"
)

func init() {
	RegisterProcessor(ProcessorRegistration{
		Type:  "kv.get",
		Title: "Get Key",
		ParamsSchema: &jsonschema.Schema{
			Type: "object",
			Properties: map[string]*jsonschema.Schema{
				"module": {
					Title:       "Module ID",
					Description: "ID of the key-value module to get the value from",
					Type:        "string",
				},
				"key": {
					Title:       "Key",
					Description: "key to retrieve from the key-value module",
					Type:        "string",
				},
			},
			Required:             []string{"module", "key"},
			AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
		},
		New: func(config config.ProcessorConfig) (Processor, error) {

			params := config.Params

			moduleIdString, err := params.GetString("module")
			if err != nil {
				return nil, fmt.Errorf("kv.get module error: %w", err)
			}

			keyString, err := params.GetString("key")
			if err != nil {
				return nil, fmt.Errorf("kv.get key error: %w", err)
			}
			return &KVGet{config: config, ModuleId: moduleIdString, Key: keyString, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
		},
	})
}

type KVGet struct {
	config   config.ProcessorConfig
	ModuleId string
	Key      string
	logger   *slog.Logger
	module   common.KeyValueModule
}

func (kvg *KVGet) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
	if kvg.module == nil {
		if wrappedPayload.Modules == nil {
			wrappedPayload.End = true
			return wrappedPayload, errors.New("kv.get wrapped payload has no modules")
		}

		module, ok := wrappedPayload.Modules[kvg.ModuleId]
		if !ok {
			wrappedPayload.End = true
			return wrappedPayload, fmt.Errorf("kv.get unable to find module with id: %s", kvg.ModuleId)
		}

		kvModule, ok := module.(common.KeyValueModule)
		if !ok {
			wrappedPayload.End = true
			return wrappedPayload, fmt.Errorf("kv.get module with id %s is not a KeyValueModule", kvg.ModuleId)
		}
		kvg.module = kvModule
	}

	value, err := kvg.module.Get(ctx, kvg.Key)
	if err != nil {
		wrappedPayload.End = true
		return wrappedPayload, fmt.Errorf("kv.get error getting key: %w", err)
	}

	wrappedPayload.Payload = value
	return wrappedPayload, nil
}

func (kvg *KVGet) Id() string {
	return kvg.config.Id
}

func (kvg *KVGet) Type() string {
	return kvg.config.Type
}
