package google

import (
	"context"
	"errors"
	"strings"

	"google.golang.org/api/idtoken"

	"github.com/pingcap/test-infra/services/tcms/service/common"
)

type googleService struct {
	oauthAudience string
}

func New(oauthAudience string) *googleService {
	if oauthAudience == "" {
		panic("google oauth audience is empty")
	}
	return &googleService{oauthAudience: oauthAudience}
}

func (s *googleService) ValidateIDToken(ctx context.Context, idToken string) (*common.OAuthResult, error) {
	payload, err := idtoken.Validate(ctx, idToken, s.oauthAudience)
	if err != nil {
		return nil, err
	}

	// extract user profile
	profile := payload.Claims
	if hd, ok := profile["hd"].(string); !ok || hd != "pingcap.com" {
		return nil, errors.New("only pingcap member can access")
	}

	res := &common.OAuthResult{}

	var ok bool
	if res.Email, ok = profile["email"].(string); !ok || !strings.HasSuffix(res.Email, "@pingcap.com") {
		return nil, errors.New("email not valid")
	}

	if profile["name"] == nil {
		res.Name = strings.Split(res.Email, "@")[0]
	} else {
		res.Name = profile["name"].(string)
	}

	if profile["picture"] != nil {
		res.Avatar = profile["picture"].(string)
	}
	return res, nil
}
