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

module.exports.create = [
  [
    body('IMEI').notEmpty().isString().withMessage(_sr.fa.required.field),
    body('renewDate').notEmpty().withMessage(_sr.fa.required.field),
    body('renewType').notEmpty().withMessage(_sr.fa.required.field),
    body('price').notEmpty().isInt().withMessage(_sr.fa.required.field)
  ],
  checkValidations(validationResult),
  async (req, res) => {
    try {
      // eslint-disable-next-line eqeqeq
      const { IMEI, renewDate, renewType, price } = req.body
      const device = await InstalledDevice.findOne({ IMEI }).populate('deviceId')
      if (!device) {
        res.status(200)
        throw new Error(_sr.fa.response.success_save + 1)
      }
      // eslint-disable-next-line eqeqeq
      if (device.status == 1) {
        const user = await User.findById(device.userId)
        const profit = price * 0.05
        const data = {
          renewDate,
          renewType,
          price,
          deviceId: device.deviceId.id,
          IMEI,
          profit,
          userId: device.userId
        }
        await Renewal.create(data)
        await Score.create({
          title: ' تمدید اشتراک',
          deviceId: device.deviceId.id,
          score: device.deviceId.score,
          userId: device.userId
        })
        user.walletBalance += data.profit
        user.score += device.deviceId.score
        user.save()
        res.status(201).json({ msg: _sr.fa.response.success_save })
      } else {
        res.status(200)
        throw new Error(_sr.fa.response.success_save + 2)
      }
    } catch (error) {
      res.json({ msg: error.message })
    }
  }
]

module.exports.findAllUser = 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 || req.query.page <= 1) {
    page = 0
  } else {
    page = (req.query.page - 1) * rows
  }

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

  let sort = {}

  // if (req.query?.deviceId_dollarProfit) {
  //     sort.dollarProfit = parseInt(req.query.deviceId_dollarProfit);
  // }
  if (req.query?.status) {
    sort.status = parseInt(req.query.status)
  }
  if (req.query?.registerDate) {
    sort.registerDate = parseInt(req.query.registerDate)
  }

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

  const filter = {
    userId: req.user_id
  }

  if (search) {
    filter.$or = [{ IMEI: { $regex: search, $options: 'i' } }]
  }

  try {
    const data = await Renewal.find(filter).skip(page).limit(rows).sort(sort).populate('deviceId')

    const total = await Renewal.countDocuments(filter)

    res.status(200).json({ data, total })
  } catch (error) {
    res.status(500).json({ message: 'An error occurred', error })
  }
}

module.exports.findAllAdmin = async (req, res) => {
  try {
    // const page = parseInt(req.query.page) || 1;
    // const rows = parseInt(req.query.rows) || 10;
    // const search = req.query.search || "";
    // const sortField = req.query.sortField || "status";
    // const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;

    // const skip     = (page - 1) * rows;

    // const filter = {};
    // if (search) {
    //     filter.$or = [
    //         { IMEI: new RegExp(search, 'i') },
    //         { 'userId.shopName': new RegExp(search, 'i') },
    //         { 'userId.national_code': new RegExp(search, 'i') },
    //     ];
    // }

    const data = await Renewal.find()
      //   .sort({ [sortField]: sortOrder })
      .populate('deviceId')
      .populate('userId', 'shopName national_code first_name last_name mobile_number city_name province_name')
    //   .skip(skip)
    //   .limit(rows);

    // const totalDocuments = await InstalledDevice.countDocuments(filter);
    // const totalPages = Math.ceil(totalDocuments / rows);

    res.status(200).json({ data })
  } catch (error) {
    console.error('Error:', error.message)
    res.status(500).json({ message: 'Server Error', error: error.message })
  }
}
