package authingcli

import (
	"fmt"
	"os"
	"testing"

	"github.com/Authing/authing-golang-sdk/v3/dto"
	"github.com/tidbcloud/devops/pkg/infra/config"
	"github.com/tidbcloud/devops/pkg/infra/utils/container"
	"github.com/tidbcloud/devops/pkg/infra/utils/test"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
)

func TestAuthingClient(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "AuthingClient Suite", test.ReporterConfig())
}

var _ = Describe("[AuthingClient]", func() {
	var cli AuthingClient

	BeforeEach(func() {

		var err error

		conf := &config.RootConfig{
			Clients: config.Clients{
				Authing: config.AuthingConfig{
					ManagementAccessKey: os.Getenv("AUTHING_AK"),
					ManagementSecretKey: os.Getenv("AUTHING_SK"),
				},
			},
		}
		cli, err = NewAuthingClient(conf)
		Expect(err).To(BeNil())
	})

	Describe("[Management]", func() {
		PIt("List users", func() {
			mgmt := cli.Management()

			page := 1
			pageLimit := 50
			emails := container.NewSet[string]()

			for {
				resp := mgmt.ListUsers(&dto.ListUsersRequestDto{
					Options: dto.ListUsersOptionsDto{
						Pagination: dto.PaginationDto{
							Page:  page,
							Limit: pageLimit,
						},
					},
				})
				Expect(resp).NotTo(BeNil())
				Expect(resp.StatusCode).To(Equal(200), fmt.Sprintf("authing list users failed: status=%d message=%s", resp.StatusCode, resp.Message))

				for _, user := range resp.Data.List {
					if user.Email == "" {
						continue
					}
					emails.Insert(user.Email)
				}

				if len(resp.Data.List) == 0 {
					break
				}
				if resp.Data.TotalCount > 0 && page*pageLimit >= resp.Data.TotalCount {
					break
				}
				page++
			}

			Expect(emails).NotTo(BeEmpty())
			fmt.Println(test.MarshalIndentOrDie(emails.Slice()))
		})
	})

})
