package svctaskrunhandler

import (
	"context"
	"testing"

	taskM "github.com/pingcap/test-infra/common/model/tcms/taskruns"
	"github.com/stretchr/testify/require"
)

type SvcTaskRefServiceStub struct {
	task *taskM.SvcTask
	err  error
}

func (s SvcTaskRefServiceStub) GetByName(ctx context.Context, name string, opts taskM.GetSvcTaskOpts) (*taskM.SvcTask, error) {
	return s.task, s.err
}

func sampleMockTask() *taskM.SvcTask {
	output := []taskM.TaskRunOutput{{Name: "output1", Value: "{{inputs.param1}}"}}
	return &taskM.SvcTask{
		Name:   "mock",
		Inputs: []taskM.TaskInputDecl{{Name: "param1"}},
		Implementation: taskM.SvcTaskImplementation{
			Mock: &taskM.MockImplementation{Outputs: output},
		}}
}

func sampleMockRun() *taskM.SvcTaskRun {
	return &taskM.SvcTaskRun{Spec: taskM.SvcTaskRunSpec{SvcTaskName: "mock", Inputs: []taskM.TaskInputBind{{Name: "param1", Value: "value of param1"}}}}
}

func TestMockHandler_OnCreate(t *testing.T) {
	h := mockHandler{SvcTaskRefServiceStub{task: sampleMockTask()}}
	created, err := h.OnCreate(context.TODO(), sampleMockRun())
	require.NoError(t, err)
	require.True(t, created.Status.Completed)
	require.Equal(t, "value of param1", created.Status.Outputs[0].Value)
}

func TestMockHandler_OnCreateFail(t *testing.T) {
	output := []taskM.TaskRunOutput{{Name: "output1", Value: "{{inputs.param1}}"}}
	h := mockHandler{SvcTaskRefServiceStub{task: &taskM.SvcTask{
		Inputs: []taskM.TaskInputDecl{{Name: "param1"}},
		Implementation: taskM.SvcTaskImplementation{
			Mock: &taskM.MockImplementation{Outputs: output},
		}}}}
	obj := taskM.SvcTaskRun{Spec: taskM.SvcTaskRunSpec{SvcTaskName: "", Inputs: []taskM.TaskInputBind{{Name: "param2", Value: "value of param1"}}}}
	created, err := h.OnCreate(context.TODO(), &obj)
	require.NoError(t, err)
	require.NotEqual(t, "", created.Status.Message)
}
