package google

import (
	"context"
	"fmt"

	"github.com/spf13/viper"
	"golang.org/x/oauth2/google"
	gs "google.golang.org/api/groupssettings/v1"
	"google.golang.org/api/option"

	"github.com/pingcap-inc/it-automation/pkg/log"
)

// GroupsSettingService represent the  Google GroupsSetting API client.
type GroupsSettingService struct {
	svc *gs.Service
}

func NewGroupsSetServiceWithCre(ctx context.Context) (*gs.Service, error) {

	svc, err := gs.NewService(ctx, option.WithCredentialsFile(viper.GetString("google.service-account")))
	// svc, err := admin.NewGroupsSettingService(ctx, options.WithTokenSource(ts))
	if err != nil {
		return nil, fmt.Errorf("google: error creating service: %v", err)
	}

	return svc, nil
}

func NewGroupsSettingService(ctx context.Context, userEmail string, serviceAccount []byte, scope ...string) (*gs.Service, error) {
	if len(scope) == 0 {
		return nil, ErrGoogleClientScopeNil
	}

	config, err := google.JWTConfigFromJSON(serviceAccount, scope...)
	if err != nil {
		return nil, fmt.Errorf("google: error getting JWT config from Service Account: %v", err)
	}

	config.Subject = userEmail
	ts := config.TokenSource(ctx)
	svc, err := gs.NewService(ctx, option.WithTokenSource(ts))
	// svc, err := admin.NewGroupsSettingService(ctx, options.WithTokenSource(ts))
	if err != nil {
		return nil, fmt.Errorf("google: error creating service: %v", err)
	}

	return svc, nil
}

func NewGroupsSetService(svc *gs.Service) (*GroupsSettingService, error) {
	return &GroupsSettingService{
		svc: svc,
	}, nil
}

// UpdateGroupOpen change groups settings.
func (grs *GroupsSettingService) UpdateGroupOpen(ctx context.Context, groupID string) {
	_, err := grs.svc.Groups.Update(groupID, &gs.Groups{
		WhoCanJoin:           "INVITED_CAN_JOIN",
		WhoCanPostMessage:    "ALL_IN_DOMAIN_CAN_POST",
		WhoCanViewMembership: "ALL_IN_DOMAIN_CAN_VIEW",
		WhoCanViewGroup:      "ALL_MEMBERS_CAN_VIEW",
	}).Do()

	if err != nil {
		log.L(ctx).Errorf("google: error updating %s group settings: %v", groupID, err)
	}

	log.L(ctx).Infof("google: update %s group settings success", groupID)
}

func (grs *GroupsSettingService) GetGroupById(ctx context.Context, groupID string) (*gs.Groups, error) {

	group, err := grs.svc.Groups.Get(groupID).Do()
	if err != nil {
		log.L(ctx).Errorf("google: error getting %s group settings: %v", groupID, err)

		return nil, err
	}

	return group, nil
}
