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

package providers

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

// create 创建 OAuth 提供商
func create(x *vigo.X, req *models.OAuthProvider) (*models.OAuthProvider, error) {
	db := cfg.DB()

	// 检查 code 是否已存在
	var count int64
	if err := db.Model(&models.OAuthProvider{}).Where("code = ?", req.Code).Count(&count).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}
	if count > 0 {
		return nil, vigo.ErrInvalidArg.WithString("provider code already exists")
	}

	// 标记为非内置
	req.IsBuiltIn = false

	// 加密 ClientSecret
	if req.ClientSecret != "" {
		encrypted, err := cfg.Global.Key.Encrypt(req.ClientSecret)
		if err != nil {
			return nil, vigo.ErrInternalServer.WithString("failed to encrypt client secret")
		}
		req.ClientSecret = encrypted
	}

	// 创建
	if err := db.Create(req).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	return req, nil
}
