package middlewares

import (
	"strings"
	"testing"

	"github.com/aws/aws-sdk-go/aws/awsutil"
	"github.com/r3labs/diff/v2"
	"github.com/snyk/driftctl/pkg/resource"
	"github.com/snyk/driftctl/pkg/resource/aws"
)

func TestAwsDefaultApiGatewayAccount_Execute(t *testing.T) {

	tests := []struct {
		name               string
		remoteResources    []*resource.Resource
		resourcesFromState []*resource.Resource
		expected           []*resource.Resource
	}{
		{
			"test that default account is not ignored when managed by IaC",
			[]*resource.Resource{
				{
					Id: "fake",
				},
				{
					Id:    "a-dummy-account",
					Type:  aws.AwsApiGatewayAccountResourceType,
					Attrs: &resource.Attributes{},
				},
				{
					Id:    "default-managed-by-IaC",
					Type:  aws.AwsApiGatewayAccountResourceType,
					Attrs: &resource.Attributes{},
				},
			},
			[]*resource.Resource{
				{
					Id:    "default-managed-by-IaC",
					Type:  aws.AwsApiGatewayAccountResourceType,
					Attrs: &resource.Attributes{},
				},
			},
			[]*resource.Resource{
				{
					Id: "fake",
				},
				{
					Id:    "default-managed-by-IaC",
					Type:  aws.AwsApiGatewayAccountResourceType,
					Attrs: &resource.Attributes{},
				},
			},
		},
		{
			"test that default account is ignored when not managed by IaC",
			[]*resource.Resource{
				{
					Id: "fake",
				},
				{
					Id:    "a-dummy-account",
					Type:  aws.AwsApiGatewayAccountResourceType,
					Attrs: &resource.Attributes{},
				},
				{
					Id:    "default-managed-by-IaC",
					Type:  aws.AwsApiGatewayAccountResourceType,
					Attrs: &resource.Attributes{},
				},
			},
			[]*resource.Resource{},
			[]*resource.Resource{
				{
					Id: "fake",
				},
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			m := NewAwsDefaultApiGatewayAccount()
			err := m.Execute(&tt.remoteResources, &tt.resourcesFromState)
			if err != nil {
				t.Fatal(err)
			}
			changelog, err := diff.Diff(tt.expected, tt.remoteResources)
			if err != nil {
				t.Fatal(err)
			}
			if len(changelog) > 0 {
				for _, change := range changelog {
					t.Errorf("%s got = %v, want %v", strings.Join(change.Path, "."), awsutil.Prettify(change.From), awsutil.Prettify(change.To))
				}
			}
		})
	}
}
