package awsauth

import (
	"context"
	"testing"

	. "github.com/onsi/gomega"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

const (
	testRoleARN = "arn:aws:iam::111122223333:role/my-node-role"
)

func TestGet(t *testing.T) {
	g := NewGomegaWithT(t)
	cli := fake.NewClientBuilder().Build()
	r := NewAwsAuthReader(cli)
	authData, err := r.Get(context.Background())
	g.Expect(client.IgnoreNotFound(err)).To(BeNil())

	initAWSAuthCM(cli)
	authData, err = r.Get(context.Background())
	g.Expect(err).To(Succeed())
	mapRole := NewRolesAuthMap(testRoleARN, "test", []string{"system:bootstrappers"})
	g.Expect(authData.ContainsMapRole(*mapRole)).To(BeTrue())
}

func TestUpdate(t *testing.T) {
	g := NewGomegaWithT(t)
	cli := fake.NewClientBuilder().Build()
	mapRoles := make([]*RolesAuthMap, 0)
	mapRoles = append(mapRoles, NewRolesAuthMap(testRoleARN, "test", []string{"system:bootstrappers"}))
	mapRoles = append(mapRoles, NewRolesAuthMap(testRoleARN, "test2", []string{"system:master"}))
	authData := AwsAuthData{
		MapRoles: mapRoles,
	}
	initAWSAuthCM(cli)
	rw := NewAwsAuthReaderWriter(cli)
	err := rw.Update(context.Background(), &authData)
	g.Expect(err).To(Succeed())
	data, err := rw.Get(context.Background())
	g.Expect(err).To(Succeed())
	g.Expect(len(data.MapRoles) == 2).To(BeTrue())
}

func initAWSAuthCM(cli client.Client) error {
	cm := &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
			Name:      AWSAuthName,
			Namespace: AWSAuthNamespace,
		},
		Data: map[string]string{
			"mapRoles": `- groups:
  - system:bootstrappers
  rolearn: arn:aws:iam::111122223333:role/my-node-role
  username: test`,
		},
	}
	return cli.Create(context.Background(), cm)
}
