package core

import (
	"testing"
)

func TestActionCreate(t *testing.T) {
	db := EphemeralDb(t)

	if err := SetAction(db, "test", "hello", []string{"echo", "hello"}); err == nil {
		t.Fatal("Action created for nonexistent source")
	}

	if err := AddSource(db, "test"); err != nil {
		t.Fatal(err)
	}

	if err := SetAction(db, "test", "hello", []string{"echo", "hello"}); err != nil {
		t.Fatal(err)
	}
	if err := SetAction(db, "test", "goodbye", []string{"exit", "1"}); err != nil {
		t.Fatal(err)
	}
	if err := SetAction(db, "test", "goodbye", []string{"echo", "goodbye"}); err != nil {
		t.Fatal(err)
	}

	actions, err := GetActionsForSource(db, "test")
	if err != nil {
		t.Fatal(err)
	}
	if len(actions) != 2 {
		t.Fatal("expected 2 actions")
	}
	found := make(map[string]bool)
	for _, action := range actions {
		found[action] = true
	}
	if !found["hello"] || !found["goodbye"] {
		t.Fatalf("missing hello and/or goodbye, got: %v", actions)
	}

	argv, err := GetArgvForAction(db, "test", "goodbye")
	if err != nil {
		t.Fatal(err)
	}
	if len(argv) != 2 || argv[0] != "echo" || argv[1] != "goodbye" {
		t.Fatalf("expected [echo goodbye], got: %v", argv)
	}

	err = DeleteAction(db, "test", "hello")
	if err != nil {
		t.Fatal(err)
	}
}