package oauth

import (
	"context"
	"errors"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"

	"security-center-backend/internal/config"
)

type GoogleClient struct {
	cfg  config.OAuthConfig
	impl *oauth2.Config
}

func NewGoogleClient(cfg config.OAuthConfig) *GoogleClient {
	clientID := cfg.GoogleClientID
	if clientID == "" {
		clientID = cfg.ClientID
	}
	clientSecret := cfg.GoogleClientSecret
	if clientSecret == "" {
		clientSecret = cfg.ClientSecret
	}
	if !cfg.Enabled || clientID == "" || clientSecret == "" {
		return &GoogleClient{cfg: cfg}
	}
	return &GoogleClient{
		cfg: cfg,
		impl: &oauth2.Config{
			ClientID:     clientID,
			ClientSecret: clientSecret,
			RedirectURL:  cfg.RedirectURL,
			Scopes:       cfg.Scopes,
			Endpoint:     google.Endpoint,
		},
	}
}

func (g *GoogleClient) AuthCodeURL(state string) (string, error) {
	if g.impl == nil {
		return "", ErrDisabled
	}
	return g.impl.AuthCodeURL(state, oauth2.AccessTypeOffline), nil
}

func (g *GoogleClient) Exchange(ctx context.Context, code string) (*oauth2.Token, error) {
	if g.impl == nil {
		return nil, ErrDisabled
	}
	return g.impl.Exchange(ctx, code)
}

var ErrDisabled = errors.New("oauth provider disabled")
