// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.

package oauth

import (
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
)

// UserInfo OIDC用户信息
func userInfo(x *vigo.X) (map[string]any, error) {
	// 从token中解析用户ID
	userID := cfg.Auth.UserID(x)
	if userID == "" {
		return nil, vigo.ErrUnauthorized
	}

	var user models.User
	if err := cfg.DB().First(&user, "id = ?", userID).Error; err != nil {
		return nil, vigo.ErrNotFound
	}

	return map[string]any{
		"sub":                user.ID,
		"name":               user.Nickname,
		"nickname":           user.Nickname,
		"preferred_username": user.Username,
		"email":              user.Email,
		"picture":            user.Avatar,
		"email_verified":     user.EmailVerified,
	}, nil
}

// OIDCDiscovery OIDC发现文档
type OIDCDiscovery struct {
	Issuer                string   `json:"issuer"`
	AuthorizationEndpoint string   `json:"authorization_endpoint"`
	TokenEndpoint         string   `json:"token_endpoint"`
	UserInfoEndpoint      string   `json:"userinfo_endpoint"`
	JWKSURI               string   `json:"jwks_uri"`
	ScopesSupported       []string `json:"scopes_supported"`
	ClaimsSupported       []string `json:"claims_supported"`
}

func discovery(x *vigo.X) (*OIDCDiscovery, error) {
	return &OIDCDiscovery{
		Issuer:                "vbase",
		AuthorizationEndpoint: "/oauth/authorize",
		TokenEndpoint:         "/oauth/token",
		UserInfoEndpoint:      "/oauth/userinfo",
		JWKSURI:               "/oauth/jwks",
		ScopesSupported:       []string{"openid", "profile", "email"},
		ClaimsSupported:       []string{"sub", "name", "nickname", "preferred_username", "email", "picture", "email_verified"},
	}, nil
}
