package cvt

import (
	"testing"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	apiv1 "github.com/tidbcloud/infra-provider/api/tidbcloud/cluster-server/v1"
)

func TestReplayDefaultResourcesReturnsDefaultsWithoutTargetSpecificNormalization(t *testing.T) {
	replay := &apiv1.Replay{
		Defaults: &apiv1.Replay_ReplayDefaults{
			Resources: &apiv1.Replay_Resources{
				InstanceType: stringPtr("c6g.8xlarge"),
				StorageSize:  stringPtr("100Gi"),
			},
		},
	}

	got := ReplayDefaultResources(replay)
	if got == nil {
		t.Fatal("ReplayDefaultResources() = nil, want defaults")
	}
	if got.InstanceType != "c6g.8xlarge" {
		t.Fatalf("ReplayDefaultResources().InstanceType = %q, want %q", got.InstanceType, "c6g.8xlarge")
	}
	if got.StorageSize != "100Gi" {
		t.Fatalf("ReplayDefaultResources().StorageSize = %q, want %q", got.StorageSize, "100Gi")
	}
}

func TestReplayTaskResourcesReturnsTaskResourcesWithoutTargetSpecificNormalization(t *testing.T) {
	replay := &apiv1.Replay{
		Defaults: &apiv1.Replay_ReplayDefaults{
			Resources: &apiv1.Replay_Resources{
				InstanceType: stringPtr("default-instance"),
				StorageSize:  stringPtr("500Gi"),
			},
		},
	}

	tests := []struct {
		name string
		task *apiv1.Replay_ReplayTask
		want *cloudv1.ReplayTaskResources
	}{
		{
			name: "empty task resources keep explicit empty instance type",
			task: &apiv1.Replay_ReplayTask{
				Resources: &apiv1.Replay_Resources{
					StorageSize: stringPtr("100Gi"),
				},
			},
			want: &cloudv1.ReplayTaskResources{
				InstanceType: "",
				StorageSize:  "100Gi",
			},
		},
		{
			name: "legacy dedicated instance type stays unchanged in cvt layer",
			task: &apiv1.Replay_ReplayTask{
				Resources: &apiv1.Replay_Resources{
					InstanceType: stringPtr("c6g.8xlarge"),
					StorageSize:  stringPtr("200Gi"),
				},
			},
			want: &cloudv1.ReplayTaskResources{
				InstanceType: "c6g.8xlarge",
				StorageSize:  "200Gi",
			},
		},
		{
			name: "task resources override defaults",
			task: &apiv1.Replay_ReplayTask{
				Resources: &apiv1.Replay_Resources{
					InstanceType: stringPtr("16C32G"),
				},
			},
			want: &cloudv1.ReplayTaskResources{
				InstanceType: "16C32G",
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := ReplayTaskResources(replay, tt.task)
			if got == nil {
				t.Fatal("ReplayTaskResources() = nil")
			}
			if got.InstanceType != tt.want.InstanceType {
				t.Fatalf("ReplayTaskResources().InstanceType = %q, want %q", got.InstanceType, tt.want.InstanceType)
			}
			if got.StorageSize != tt.want.StorageSize {
				t.Fatalf("ReplayTaskResources().StorageSize = %q, want %q", got.StorageSize, tt.want.StorageSize)
			}
		})
	}
}

func TestReplayDefaultResourcesWithoutDefaultsReturnsNil(t *testing.T) {
	replay := &apiv1.Replay{}
	if got := ReplayDefaultResources(replay); got != nil {
		t.Fatalf("ReplayDefaultResources() = %#v, want nil without defaults", got)
	}
}

func stringPtr(s string) *string {
	return &s
}
