package dataplane

import (
	"context"
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/tidbcloud/eks-provider/controllers/workflow/action"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
)

func Test_precheck(t *testing.T) {
	tests := []struct {
		name     string
		workflow cloudv1.Workflow
		action   action.Action
		expected error
	}{
		{
			name: "restart pod action",
			workflow: cloudv1.Workflow{
				Spec: cloudv1.WorkflowSpec{
					Steps: []cloudv1.WorkflowStep{
						{
							Name: "restart pod",
							Inputs: cloudv1.InputsWrapper{Object: map[string]interface{}{
								"namespace": "abc", "clusterName": "xyz", "podName": "pod-1", "force": true,
							}},
						},
					},
				},
			},
			action:   &restartPod{},
			expected: nil,
		},
		{
			name: "restart pod action with mismatch input field should fail to decode",
			workflow: cloudv1.Workflow{
				Spec: cloudv1.WorkflowSpec{
					Steps: []cloudv1.WorkflowStep{
						{
							Name: "restart pod",
							Inputs: cloudv1.InputsWrapper{Object: map[string]interface{}{
								"namespace": "abc", "clusterName": "xyz", "podName": "pod-1", "force": "true",
							}},
						},
					},
				},
			},
			action:   &restartPod{},
			expected: fmt.Errorf("decode inputs"),
		},
		{
			name: "restart pod action omit podName should fail to validate",
			workflow: cloudv1.Workflow{
				Spec: cloudv1.WorkflowSpec{
					Steps: []cloudv1.WorkflowStep{
						{
							Name: "restart pod",
							Inputs: cloudv1.InputsWrapper{Object: map[string]interface{}{
								"namespace": "abc", "clusterName": "xyz", "force": true,
							}},
						},
					},
				},
			},
			action:   &restartPod{},
			expected: fmt.Errorf("validate inputs"),
		},
		{
			name: "restart pod action omit force field is ok",
			workflow: cloudv1.Workflow{
				Spec: cloudv1.WorkflowSpec{
					Steps: []cloudv1.WorkflowStep{
						{
							Name: "restart pod",
							Inputs: cloudv1.InputsWrapper{Object: map[string]interface{}{
								"namespace": "abc", "clusterName": "xyz", "podName": "pod-1",
							}},
						},
					},
				},
			},
			action:   &restartPod{},
			expected: nil,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ctx := context.TODO()
			err := tt.action.PreCheck(ctx, &tt.workflow, tt.workflow.Spec.Steps[0])
			if tt.expected == nil {
				assert.Nil(t, err, "precheck: "+tt.name)
			} else {
				assert.ErrorContains(t, err, tt.expected.Error(), "precheck: "+tt.name)
			}
		})
	}
}
