package oauth_provider

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"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"
	"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 GetOauthProviderListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetOauthProviderListLogic) GetOauthProviderList(in *core.OauthProviderReq) (*core.OauthProviderListResp, error) {
	var predicates []predicate.OauthProvider
	if in.Name != "" {
		predicates = append(predicates, oauthprovider.NameContains(in.Name))
	}
	if in.ClientId != "" {
		predicates = append(predicates, oauthprovider.ClientIDContains(in.ClientId))
	}
	if in.System != nil {
		predicates = append(predicates, oauthprovider.SystemEQ(in.GetSystem()))
	}
	if in.Init != nil {
		predicates = append(predicates, oauthprovider.InitEQ(in.GetInit()))
	}
	query := l.svcCtx.DB.OauthProvider.Query().Where(predicates...)
	var (
		pagination *core.Pagination
		list       []*ent.OauthProvider
		err        error
	)
	if in.Page != nil {
		result, pageErr := query.Page(l.ctx, in.Page.Current, in.Page.Size)
		if pageErr == nil {
			pagination = utils.ConvertPaginationDb(result.PageDetails)
			list = result.List
		} else {
			err = pageErr
		}
	} else {
		list, err = query.All(l.ctx)
	}
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	resp := &core.OauthProviderListResp{
		Page: pagination,
		Data: make([]*core.OauthProviderInfo, len(list)),
	}

	for i, v := range list {
		resp.Data[i] = l.svcCtx.Convert.ConvertOAuthProviderRpc(l.ctx, v)
	}
	return resp, nil
}
