package api

import (
	"testing"

	"code.fbi.h-da.de/danet/api/go/gosdn/pnd"
	tpb "code.fbi.h-da.de/danet/api/go/gosdn/transport"
	"github.com/google/uuid"
	guuid "github.com/google/uuid"
	"github.com/spf13/viper"
)

func TestApiIntegration(t *testing.T) {
	// TDOO: Remove once openshift grpc support is available
	t.Skip("skipped due to openshift limitations")
	if testing.Short() {
		t.Skip("skipping integration test")
	}
	tests := []struct {
		name    string
		wantErr bool
	}{
		{
			name:    "default",
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			defer viper.Reset()
			if err := Init(testAPIEndpoint); (err != nil) != tt.wantErr {
				switch err.(type) {
				case viper.ConfigFileNotFoundError:
				default:
					t.Errorf("gosdn cli init error = %v, wantErr %v", err, tt.wantErr)
					return
				}
			}
			cliPnd := viper.GetString("CLI_PND")
			cliSbi := viper.GetString("CLI_SBI")

			suid, err := uuid.Parse(cliSbi)
			if err != nil {
				t.Error(err)
			}
			puid, err := uuid.Parse(cliPnd)
			if err != nil {
				t.Error(err)
			}

			opt := &tpb.TransportOption{
				Address:  testAddress,
				Username: testUsername,
				Password: testPassword,
				TransportOption: &tpb.TransportOption_GnmiTransportOption{
					GnmiTransportOption: &tpb.GnmiTransportOption{},
				},
			}
			if _, err := addDevice(
				testAPIEndpoint,
				"test-device",
				opt,
				suid,
				puid,
			); (err != nil) != tt.wantErr {
				t.Errorf("gosdn cli add-device error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			did := viper.GetString("LAST_DEVICE_UUID")

			_, err = getDevice(
				testAPIEndpoint,
				cliPnd,
				did,
			)
			if (err != nil) != tt.wantErr {
				t.Errorf("gosdn cli request error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			_, err = getDevice(
				testAPIEndpoint,
				cliPnd,
				"",
				did,
			)
			if (err != nil) != tt.wantErr {
				t.Errorf("gosdn cli get-device error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			hostname := guuid.New().String()
			_, err = changeRequest(
				testAPIEndpoint,
				did,
				cliPnd,
				testPath,
				hostname,
				pnd.ApiOperation_UPDATE,
			)
			if (err != nil) != tt.wantErr {
				t.Errorf("gosdn cli set error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			resp, err := getDevice(testAddress, testUsername, testPassword, testPath)
			if err != nil {
				if !tt.wantErr {
					t.Errorf("Get() error = %v, wantErr %v", err, tt.wantErr)
				}
				return
			}
			var got string
			if resp != nil {
				got = resp.Ond[0].Name
			} else {
				t.Errorf("integration test failed got cannot be nil")
			}
			if got != hostname {
				t.Errorf("integration test failed = got: %v, want: %v", got, hostname)
			}
		})
	}
}