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/ent/predicate"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"

	"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 GetOauthProviderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetOauthProviderLogic) GetOauthProvider(in *core.OauthProviderReq) (*core.OauthProviderInfo, error) {
	var predicates []predicate.OauthProvider
	if in.ID != 0 {
		predicates = append(predicates, oauthprovider.IDEQ(in.ID))
		goto Query
	}
	if in.ClientId != "" {
		predicates = append(predicates, oauthprovider.ClientIDEQ(in.ClientId))
		goto Query
	}
	if in.Name != "" {
		predicates = append(predicates, oauthprovider.NameContains(in.Name))
	}
	if in.System != nil {
		predicates = append(predicates, oauthprovider.SystemEQ(in.GetSystem()))
	}
	if in.Init != nil {
		predicates = append(predicates, oauthprovider.InitEQ(in.GetInit()))
	}
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	dbData, err := l.svcCtx.DB.OauthProvider.Query().
		Where(predicates...).
		First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}

	resp := l.svcCtx.Convert.ConvertOAuthProviderRpc(l.ctx, dbData)
	return resp, nil
}
