// const { body, param, validationResult } = require('express-validator')
// const { _sr } = require('../plugins/serverResponses')
// const { checkValidations } = require('../plugins/controllersHelperFunctions')
const Score = require('../models/GPS.Score')
const User = require('../models/GPS.User')

module.exports.getAll = async (req, res) => {
  let page
  let rows

  if (!req.query?.rows || req.query?.rows <= 5) {
    rows = 10
  } else {
    rows = parseInt(req.query.rows)
  }

  if (!req.query?.page) {
    page = 0
  } else if (req.query.page <= 1) {
    page = 0
  } else {
    page = req.query.page
    page = page * rows - rows
  }

  const search = req.query?.search ? req.query.search : null

  let sort = {}

  if (req.query?.created_at) {
    sort.created_at = parseInt(req.query.created_at)
  }

  if (req.query?.score) {
    sort.score = parseInt(req.query.score)
  }

  if (Object.keys(sort).length === 0) {
    sort = { created_at: -1 }
  }

  const filter = {
    userId: req.user_id
  }

  if (search) {
    filter.$or = [{ title: new RegExp(search, 'i') }, ...(!isNaN(search) ? [{ score: Number(search) }] : [])]
  }

  const score = await Score.find(filter).skip(page).limit(rows).sort(sort)
  const userScore = await User.findById(req.user_id).select('score totalScore')
  const total = Math.ceil(await Score.countDocuments(filter))

  const user = await User.findById(req.user_id).select('score totalScore')
  res.status(200).json({ data: score, score: user.score, total, totalScore: userScore.totalScore })
}
