package tenant

import (
	"fmt"

	"github.com/pkg/errors"
	"github.com/tidbcloud/config-service/pkg/auth"
	"github.com/tidbcloud/config-service/pkg/central"
)

// Lister list TiDB Cloud tenants from meta store
type Lister interface {
	List() ([]central.Tenant, error)
}

type dbaasTenantLister struct {
	host string

	centralSvc *central.Service
}

func NewLister(host string, auth *auth.Auth0ClientAuth) Lister {
	centralSvc := central.NewService(fmt.Sprintf("http://%s", host), auth.Domain, auth.ClientID, auth.ClientSecret, auth.Audience)
	return &dbaasTenantLister{host: host, centralSvc: centralSvc}
}

var _ Lister = &dbaasTenantLister{}

func (l *dbaasTenantLister) List() ([]central.Tenant, error) {
	resp, err := l.centralSvc.ListTenants()
	if err != nil {
		return nil, errors.Wrap(err, "error list tenants")
	}
	var tList []central.Tenant
	for _, t := range resp.Items {
		// only reconcile active tenant
		if t.Status != "active" {
			continue
		}
		tList = append(tList, t)
	}
	return tList, nil
}
