package user_social

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

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

func (l *GetUserSocialLogic) GetUserSocial(in *core.UserSocialReq) (*core.UserSocialInfo, error) {
	var predicates []predicate.UserSocial
	if in.ID != 0 {
		predicates = append(predicates, usersocial.IDEQ(in.ID))
		goto Query
	}
	if in.UserId != 0 {
		predicates = append(predicates, usersocial.UserIDEQ(in.UserId))
	}
	if in.Provider != "" {
		predicates = append(predicates, usersocial.ProviderEQ(in.Provider))
	}
	if in.AccessToken != "" {
		predicates = append(predicates, usersocial.AccessTokenEQ(in.AccessToken))
	}
	if in.Uid != "" {
		predicates = append(predicates, usersocial.UIDEQ(in.Uid))
	}
	if in.OpenId != "" {
		predicates = append(predicates, usersocial.OpenID(in.OpenId))
	}
	if in.UnionId != "" {
		predicates = append(predicates, usersocial.UnionIDEQ(in.UnionId))
	}
	if len(predicates) == 0 {
		return nil, nil
	}
Query:
	query := l.svcCtx.DB.UserSocial.Query().Where(predicates...)
	if in.WithUser {
		query.WithUser()
	}
	dbData, err := query.First(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	return l.svcCtx.Convert.ConvertUserSocialRpc(l.ctx, dbData), nil
}
