package user_social

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

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

func (l *GetUserSocialListLogic) GetUserSocialList(in *core.UserSocialReq) (*core.UserSocialListResp, 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))
	}
Query:
	query := l.svcCtx.DB.UserSocial.Query().Where(predicates...)
	if in.WithUser {
		query.WithUser()
	}
	var (
		pagination *core.Pagination
		list       []*ent.UserSocial
		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.UserSocialListResp{
		Page: pagination,
		Data: make([]*core.UserSocialInfo, len(list)),
	}

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