/*
Copyright 2019 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package awsup

import (
	"context"
	"reflect"
	"testing"

	"github.com/aws/aws-sdk-go-v2/aws"
	ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
	"k8s.io/kops/pkg/apis/kops"
)

func TestValidateRegion(t *testing.T) {
	ctx := context.Background()
	allRegions = []ec2types.Region{
		{
			RegionName: aws.String("us-test-1"),
		},
		{
			RegionName: aws.String("us-test-2"),
		},
	}
	for _, region := range []string{"us-test-1", "us-test-2"} {
		err := ValidateRegion(ctx, region)
		if err != nil {
			t.Fatalf("unexpected error validating region %q: %v", region, err)
		}
	}

	for _, region := range []string{"is-lost-1", "no-road-2", "no-real-3"} {
		err := ValidateRegion(ctx, region)
		if err == nil {
			t.Fatalf("expected error validating region %q", region)
		}
	}
}

func TestFindRegion(t *testing.T) {
	for _, zone := range []string{"us-east-1a", "us-east-1b", "us-east-1c", "us-east-2a", "us-east-2b", "us-east-2c"} {
		c := &kops.Cluster{}
		c.Spec.Networking.Subnets = append(c.Spec.Networking.Subnets, kops.ClusterSubnetSpec{Name: "subnet-" + zone, Zone: zone})

		region, err := FindRegion(c)
		if err != nil {
			t.Fatalf("unexpected error finding region for %q: %v", zone, err)
		}

		expected := zone[:len(zone)-1]
		if region != expected {
			t.Fatalf("unexpected region for zone: %q vs %q", expected, region)
		}
	}

	testCases := []struct {
		name        string
		subnets     []kops.ClusterSubnetSpec
		expected    string
		expectError bool
	}{
		{
			name: "ignores subnets specified by ID without a zone",
			subnets: []kops.ClusterSubnetSpec{
				{Name: "subnet-a", ID: "subnet-12345678"},
				{Name: "subnet-b", Zone: "us-east-2b"},
			},
			expected: "us-east-2",
		},
		{
			name: "errors when no subnet specifies a zone",
			subnets: []kops.ClusterSubnetSpec{
				{Name: "subnet-a", ID: "subnet-12345678"},
			},
			expectError: true,
		},
		{
			name: "errors when a subnet has neither zone nor ID",
			subnets: []kops.ClusterSubnetSpec{
				{Name: "subnet-a"},
				{Name: "subnet-b", Zone: "us-east-2b"},
			},
			expectError: true,
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c := &kops.Cluster{}
			c.Spec.Networking.Subnets = tc.subnets

			region, err := FindRegion(c)
			if tc.expectError {
				if err == nil {
					t.Fatalf("expected error finding region, got %q", region)
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error finding region: %v", err)
			}
			if region != tc.expected {
				t.Fatalf("unexpected region: %q vs %q", region, tc.expected)
			}
		})
	}
}

func TestSupportsS3BootstrapEndpoint(t *testing.T) {
	for _, tc := range []struct {
		region    string
		supported bool
	}{
		{region: "us-east-1", supported: true},
		{region: "us-gov-west-1", supported: true},
		{region: "cn-north-1"},
		{region: "us-iso-east-1"},
		{region: "us-isob-east-1"},
		{region: "eu-isoe-west-1"},
		{region: "us-isof-south-1"},
		{region: "eusc-de-east-1"},
	} {
		t.Run(tc.region, func(t *testing.T) {
			supported, err := SupportsS3BootstrapEndpoint(context.Background(), tc.region)
			if err != nil {
				t.Fatalf("checking S3 bootstrap endpoint support: %v", err)
			}
			if supported != tc.supported {
				t.Errorf("supported=%v, expected %v", supported, tc.supported)
			}
		})
	}
}

func TestEC2TagSpecification(t *testing.T) {
	cases := []struct {
		Name          string
		ResourceType  ec2types.ResourceType
		Tags          map[string]string
		Specification []ec2types.TagSpecification
	}{
		{
			Name: "No tags",
		},
		{
			Name:         "simple tag",
			ResourceType: ec2types.ResourceTypeVpc,
			Tags: map[string]string{
				"foo": "bar",
			},
			Specification: []ec2types.TagSpecification{
				{
					ResourceType: ec2types.ResourceTypeVpc,
					Tags: []ec2types.Tag{
						{
							Key:   aws.String("foo"),
							Value: aws.String("bar"),
						},
					},
				},
			},
		},
	}
	for _, tc := range cases {
		t.Run(tc.Name, func(t *testing.T) {
			s := EC2TagSpecification(tc.ResourceType, tc.Tags)
			if !reflect.DeepEqual(s, tc.Specification) {
				t.Fatalf("tag specifications did not match: %+v vs %+v", s, tc.Specification)
			}
		})
	}
}

func Test_GetResourceName32(t *testing.T) {
	grid := []struct {
		ClusterName string
		Prefix      string
		Expected    string
	}{
		{
			"mycluster",
			"bastion",
			"bastion-mycluster-vnrjie",
		},
		{
			"mycluster.example.com",
			"bastion",
			"bastion-mycluster-example-o8elkm",
		},
		{
			"this.is.a.very.long.cluster.example.com",
			"api",
			"api-this-is-a-very-long-c-q4ukp4",
		},
		{
			"this.is.a.very.long.cluster.example.com",
			"bastion",
			"bastion-this-is-a-very-lo-4ggpa2",
		},
	}
	for _, g := range grid {
		actual := GetResourceName32(g.ClusterName, g.Prefix)
		if actual != g.Expected {
			t.Errorf("unexpected result from %q+%q.  expected %q, got %q", g.Prefix, g.ClusterName, g.Expected, actual)
		}
	}
}
