//
// 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"
)

// UpdateRequest 更新请求
type UpdateRequest struct {
	Code string `src:"path@code" desc:"提供商代码"`
	models.OAuthProvider
}

// update 更新 OAuth 提供商
func update(x *vigo.X, req *UpdateRequest) (*models.OAuthProvider, error) {
	db := cfg.DB()

	// 查找现有配置
	var provider models.OAuthProvider
	if err := db.Where("code = ?", req.Code).First(&provider).Error; err != nil {
		return nil, vigo.ErrNotFound.WithError(err)
	}

	// 内置的不能修改 code
	if provider.IsBuiltIn && req.OAuthProvider.Code != req.Code {
		return nil, vigo.ErrForbidden.WithString("cannot change code of built-in provider")
	}

	// 更新字段（保留 id 和 is_built_in）
	req.ID = provider.ID
	req.IsBuiltIn = provider.IsBuiltIn

	// 如果提供了新的 ClientSecret，则加密；否则保留原值
	if req.OAuthProvider.ClientSecret != "" {
		encrypted, err := cfg.Global.Key.Encrypt(req.OAuthProvider.ClientSecret)
		if err != nil {
			return nil, vigo.ErrInternalServer.WithString("failed to encrypt client secret")
		}
		req.OAuthProvider.ClientSecret = encrypted
	} else {
		req.OAuthProvider.ClientSecret = provider.ClientSecret
	}

	if err := db.Save(&req.OAuthProvider).Error; err != nil {
		return nil, vigo.ErrInternalServer.WithError(err)
	}

	return &req.OAuthProvider, nil
}
