package cmdpacks

import (
	"context"
	"lmika.dev/cmd/dynamo-browse/internal/dynamo-browse/services"
	"ucl.lmika.dev/ucl"
)

type pbModule struct {
	pasteboardProvider services.PasteboardProvider
}

func (m pbModule) pbGet(ctx context.Context, args ucl.CallArgs) (any, error) {
	s, ok := m.pasteboardProvider.ReadText()
	if !ok {
		return "", nil
	}
	return s, nil
}

func (m pbModule) pbPut(ctx context.Context, args ucl.CallArgs) (any, error) {
	var s string
	if err := args.Bind(&s); err != nil {
		return nil, err
	}
	if err := m.pasteboardProvider.WriteText([]byte(s)); err != nil {
		return nil, err
	}
	return s, nil
}

func modulePB(
	pasteboardProvider services.PasteboardProvider,
) ucl.Module {
	m := &pbModule{
		pasteboardProvider: pasteboardProvider,
	}

	return ucl.Module{
		Name: "pb",
		Builtins: map[string]ucl.BuiltinHandler{
			"paste": m.pbGet,
			"copy":  m.pbPut,
		},
	}
}
