package user

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

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

func (l *GetUserListLogic) GetUserList(in *core.UserReq) (*core.UserListResp, error) {
	var predicates []predicate.User
	if in.Username != "" {
		predicates = append(predicates, user.UsernameContains(in.Username))
	}
	if in.PhoneNumber != "" {
		predicates = append(predicates, user.PhoneNumberContains(in.PhoneNumber))
	}
	if in.Email != "" {
		predicates = append(predicates, user.EmailContains(in.Email))
	}
	if in.Nickname != "" {
		predicates = append(predicates, user.NicknameContains(in.Nickname))
	}
	query := l.svcCtx.DB.User.Query().
		Where(predicates...).
		WithLoginRecord()
	if in.WithRole {
		query.WithRoles()
	}
	if in.WithSocial {
		query.WithSocials()
	}
	if in.WithDepartment {
		query.WithDepartments()
	}
	if in.WithToken {
		query.WithToken()
	}

	var (
		pagination *core.Pagination
		list       []*ent.User
		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.UserListResp{
		Page: pagination,
		Data: make([]*core.UserInfo, len(list)),
	}

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