package authentik

import "strings"

type OAuthPreset struct {
	ProviderType      string
	AuthorizationURL  string
	AccessTokenURL    string
	ProfileURL        string
	DefaultScopes     string
	OrganizationClaim string
}

func OAuthPresetFor(provider string) OAuthPreset {
	switch strings.ToLower(strings.TrimSpace(provider)) {
	case "google":
		return OAuthPreset{
			ProviderType:      "google",
			AuthorizationURL:  "https://accounts.google.com/o/oauth2/auth",
			AccessTokenURL:    "https://oauth2.googleapis.com/token",
			ProfileURL:        "https://www.googleapis.com/oauth2/v1/userinfo",
			DefaultScopes:     "openid email profile",
			OrganizationClaim: "hd",
		}
	case "github":
		return OAuthPreset{
			ProviderType:      "github",
			AuthorizationURL:  "https://github.com/login/oauth/authorize",
			AccessTokenURL:    "https://github.com/login/oauth/access_token",
			ProfileURL:        "https://api.github.com/user",
			DefaultScopes:     "read:user user:email",
			OrganizationClaim: "org",
		}
	case "linkedin":
		return OAuthPreset{
			ProviderType:      "openidconnect",
			AuthorizationURL:  "https://www.linkedin.com/oauth/v2/authorization",
			AccessTokenURL:    "https://www.linkedin.com/oauth/v2/accessToken",
			ProfileURL:        "https://api.linkedin.com/v2/userinfo",
			DefaultScopes:     "openid profile email",
			OrganizationClaim: "",
		}
	case "microsoft":
		return OAuthPreset{
			ProviderType:      "azuread",
			AuthorizationURL:  "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
			AccessTokenURL:    "https://login.microsoftonline.com/common/oauth2/v2.0/token",
			ProfileURL:        "https://graph.microsoft.com/oidc/userinfo",
			DefaultScopes:     "openid email profile",
			OrganizationClaim: "tid",
		}
	default:
		return OAuthPreset{
			ProviderType:  "openidconnect",
			DefaultScopes: "openid email profile",
		}
	}
}

func OAuthRedirectURI(publicBaseURL, slug string) string {
	base := strings.TrimRight(strings.TrimSpace(publicBaseURL), "/")
	if base == "" {
		base = "http://localhost/auth"
	}
	return base + "/source/oauth/callback/" + strings.TrimSpace(slug) + "/"
}

func AuthentikPublicBaseURL(apiURL string, publicHTTPS bool) string {
	apiURL = strings.TrimSpace(apiURL)
	if apiURL == "" {
		if publicHTTPS {
			return "https://localhost/auth"
		}
		return "http://localhost/auth"
	}
	u := strings.TrimSuffix(apiURL, "/")
	u = strings.TrimSuffix(u, "/api/v3")
	if publicHTTPS && strings.HasPrefix(u, "http://") {
		u = "https://" + strings.TrimPrefix(u, "http://")
	}
	return u
}
