package oauth_provider

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/oauthprovider"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"

	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
)

type UpdateOauthProviderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateOauthProviderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateOauthProviderLogic {
	return &UpdateOauthProviderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateOauthProviderLogic) UpdateOauthProvider(in *core.OauthProviderInfo) (*core.BaseResp, error) {
	update := l.svcCtx.DB.OauthProvider.Update().
		Where(oauthprovider.IDEQ(in.ID)).
		SetNotEmptyName(in.Name).
		SetNotEmptyClientID(in.ClientId).
		SetNotEmptyClientSecret(in.ClientSecret).
		SetNotEmptyRedirectURL(in.RedirectUrl).
		SetNotEmptyScopes(in.Scopes).
		SetNotEmptyAuthURL(in.AuthUrl).
		SetNotEmptyTokenURL(in.TokenUrl).
		SetNotEmptyInfoURL(in.InfoUrl).
		SetNotEmptyDescription(in.Description)
	if in.ClientId != "" && in.ClientSecret != "" {
		update.SetInit(true)
	}
	err := update.Exec(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}

	return &core.BaseResp{
		Code: code.StatusOK,
		Msg:  msg.UpdateSuccess,
	}, nil
}
