package auth

import (
	"strings"
	"sync"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
)

var (
	ConsumerPoolId  string
	cognitoOnce     sync.Once
	cognitoInstance *cognitoidentityprovider.CognitoIdentityProvider
)

func GetUsersList(users []string) ([]common.JSONUserProfile, error) {
	var userList []common.JSONUserProfile

	for _, userid := range users {
		cognitoClient := getAWS()

		filter := strings.Replace("username = \"userId\"", "userId", userid, -1)

		request := &cognitoidentityprovider.ListUsersInput{
			Filter:     &filter,
			UserPoolId: &ConsumerPoolId,
		}
		resp, err := cognitoClient.ListUsers(request)
		if err != nil {
			return nil, err
		}

		userList = append(userList, convertAWSUsers(resp.Users)...)
	}

	return userList, nil
}

func convertAWSUsers(users []*cognitoidentityprovider.UserType) []common.JSONUserProfile {
	var userList []common.JSONUserProfile

	for _, user := range users {
		userList = append(userList, findUserAttributes(user))
	}

	return userList
}

func findUserAttributes(awsUser *cognitoidentityprovider.UserType) common.JSONUserProfile {
	attributes := awsUser.Attributes
	user := common.JSONUserProfile{}

	user.UserName = *awsUser.Username
	for _, attribute := range attributes {
		switch *attribute.Name {
		case "email":
			user.Email = *attribute.Value
		case "phone_number":
			user.Phone = *attribute.Value
		case "given_name":
			user.FirstName = *attribute.Value
		case "family_name":
			user.LastName = *attribute.Value
		}
	}

	return user
}

func getAWS() *cognitoidentityprovider.CognitoIdentityProvider {
	cognitoOnce.Do(func() {
		if cognitoInstance != nil {
			return
		}
		logger.Info().Msg("Init cognito provider instance")
		setPoolId()
		mySession := session.Must(session.NewSession())
		cognitoInstance = cognitoidentityprovider.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
	})

	return cognitoInstance
}

func setPoolId() {
	//default to dev pool
	ConsumerPoolId = envtool.GetEnv("CONSUMER_COGNITO_CLIENT_ID", "us-west-2_c7Qu91m3J")
}
