package googlecli

import (
	"context"
	"fmt"
	"os"
	"testing"

	"cloud.google.com/go/bigquery"
	"github.com/tidbcloud/devops/pkg/infra/utils/test"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/iterator"

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

func TestGoogleCli(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Google Client Suite", test.ReporterConfig())
}

// Default to pending, run it if you want to test client.
var _ = Describe("[GoogleClient]", func() {
	var (
		credFile  = os.Getenv("GCP_SA_CRED_FILE")
		projectID = "gcp-resilience-dev"
		bgcli     BigQueryCli
		adcli     AdminCli
		bgRaw     *bigQueryClient
		adRaw     *adminClient
	)

	BeforeEach(func() {
		var err error

		content, err := os.ReadFile(credFile)
		Expect(err).To(BeNil())

		cred, err := google.CredentialsFromJSONWithTypeAndParams(context.Background(), content, google.ServiceAccount, google.CredentialsParams{
			Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
		})
		Expect(err).To(BeNil())

		bgcli, err = NewBigQueryClientFromCred(context.Background(), cred, projectID)
		Expect(err).To(BeNil())

		adcli, err = NewAdminClientFromCred(context.Background(), content)
		Expect(err).To(BeNil())

		bgRaw = bgcli.(*bigQueryClient)
		adRaw = adcli.(*adminClient)
	})

	Describe("Have a try", func() {
		PIt("list soc2", func() {
			emails, err := adRaw.ListUserEmailsFromSoc2Group()
			Expect(err).To(BeNil())

			fmt.Println(test.MarshalIndentOrDie(emails))
		})

		PIt("list datasets", func() {
			ctx := context.Background()
			iter := bgRaw.bigQueryCli.Datasets(ctx)

			for {
				ds, err := iter.Next()
				if err == iterator.Done {
					break
				}
				Expect(err).To(BeNil())

				meta, err := ds.Metadata(ctx)
				Expect(err).To(BeNil())

				fmt.Println(test.MarshalIndentOrDie(meta))
			}
		})

		PIt("query", func() {
			ctx := context.Background()

			iter, err := bgRaw.Query(ctx,
				fmt.Sprintf(`
				SELECT
					*
				FROM %s
				LIMIT 10
				`, "gcp-digital-bi.model_tidbcloud.dws_cloud_tenants_basicinfo",
				),
			)
			Expect(err).To(BeNil())

			for {
				v := map[string]bigquery.Value{}
				err := iter.Next(&v)
				if err == iterator.Done {
					break
				}
				Expect(err).To(BeNil())

				fmt.Println(test.MarshalIndentOrDie(v))
			}
		})
	})
})
