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

module.exports.createRequest = [
  [
    body('card').notEmpty().isObject().withMessage('گارت ورودی خود را انتخاب کنید'),
    body('amount').notEmpty().isNumeric().withMessage('مقدار را وارد کنید')
  ],
  checkValidations(validationResult), 
  async (req, res) => {
    try {
      const withdraw = await Withdraw.findOne({ userId: req.user_id, status: 0 })
      if (withdraw) {
        res.status(400).json({ msg: 'شما درخواست درحال بررسی دارید' })
      } else {
        const user = await User.findById(req.user_id)
        if (!user) {
          return res.status(400).json({ msg: 'کاربر یافت نشد' })
        }
        if (req.body.amount > user.walletBalance) {
          return res.status(400).json({ msg: 'موجودی شما کافی نیست' })
        }
        if (user.walletBalance >= 50000) {
          const data = {
            card: req.body.card,
            userId: req.user_id,
            amount: req.body.amount,
            // dollarAmount: user.dollarBalance,
            status: 0
          }

          const request = await Withdraw.create(data)
          //   user.dollarBalance = 0
          user.walletBalance -= req.body.amount
          user.save()
          // res.status(201).json({ msg: _sr.fa.response.success_save, data: request })
          notifyAdmin('newWithdrawRequest')
          res.status(201).json(request)
        } else {
          res.status(400).json({ msg: 'حداقل موجودی باید 50 هزار تومان باشد' })
        }
      }
    } catch (error) {
      res.status(500).json({ msg: error })
    }
  }
]

module.exports.cancellRequest = async (req, res) => {
  try {
    // Find the latest request with status 0 for the current user
    const withdraw = await Withdraw.findOne({ userId: req.user_id, status: 0 })
      .sort({ _id: -1 }) // Get the latest one
    
    if (!withdraw) {
      return res.status(404).json({ msg: 'درخواست در حال بررسی یافت نشد' })
    }

    // Restore the wallet balance
    const user = await User.findById(req.user_id)
    if (user) {
      user.walletBalance += withdraw.amount
      await user.save()
    }

    // Delete the request
    await Withdraw.findByIdAndDelete(withdraw._id)

    res.status(200).json({ msg: 'درخواست با موفقیت لغو شد' })
  } catch (error) {
    res.status(500).json({ msg: error.message || error })
  }
}

module.exports.getAllForUser = async (req, res) => {
  const rows = !req.query?.rows || req.query?.rows <= 5 ? 10 : parseInt(req.query.rows)

  let page = 0
  if (req.query?.page && req.query.page > 1) {
    page = (req.query.page - 1) * rows
  }

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

  let sort = {}

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

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

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

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

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

  const filter = {
    userId: req.user_id
  }

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

  try {
    const data = await Withdraw.find(filter).skip(page).limit(rows).sort(sort)
    const total = await Withdraw.countDocuments(filter)

    res.status(200).json({ data, total })
  } catch (error) {
    res.status(500).json({ message: 'خطای سرور', error })
  }
}

module.exports.getAllForAdmin = 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 matchStage = search
      ? {
          $or: [{ IMEI: new RegExp(search, 'i') }, { trackingNumber: new RegExp(search, 'i') }]
        }
      : {}

    // const aggregationPipeline = [
    //   { $match: matchStage },
    //   {
    //     $lookup: {
    //       from: 'usergps',
    //       localField: 'userId',
    //       foreignField: '_id',
    //       as: 'userId'
    //     }
    //   },
    //   { $unwind: '$userId' },
    //   { $sort: { [sortField]: sortOrder } },
    //   { $skip: skip },
    //   { $limit: rows }
    // ]
    // const data = await Withdraw.aggregate(aggregationPipeline)
    const data = await Withdraw.find(matchStage)
      .sort({ [sortField]: sortOrder })
      .skip(skip)
      .limit(rows)
      .populate('userId')

    const totalDocuments = await Withdraw.countDocuments(matchStage)

    // const [data, totalDocuments] = await Promise.all([
    //   Withdraw.aggregate(aggregationPipeline),
    //   Withdraw.countDocuments(matchStage)
    // ])

    const totalPages = Math.ceil(totalDocuments / rows)

    res.status(200).json({ data, totalDocuments, totalPages })
  } catch (error) {
    res.status(500).json({ message: 'An error occurred, please try again.', error: error.message })
  }
}

module.exports.updateReq = [
  [
    param('id').notEmpty().isMongoId().withMessage('ایدی را باید وارد کنید'),
    param('type').notEmpty().isString().withMessage('وضعیت را باید وارد کنید')
  ],
  checkValidations(validationResult),
  async (req, res) => {
    const request = await Withdraw.findById(req.params.id)
    if (!request) {
      res.status(404).json({ msg: _sr.fa.not_found.item_id })
    } else {
      switch (req.params.type) {
        case 'accept': {
          request.status = 1
          request.save()
          notifyAdmin('newWithdrawRequest')

          res.status(201).json({ msg: _sr.fa.response.success_save, data: request })

          break
        }
        case 'deposit': {
          request.status = 2
          request.depositDate = new Date()
          request.trackingNumber = req.body.trackingNumber || 0
          request.save()
          notifyAdmin('newWithdrawRequest')

          res.status(201).json({ msg: _sr.fa.response.success_save, data: request })

          break
        }
        default: {
          res.status(404).json({ msg: 'استاتوس اشتباه است' })
          break
        }
      }
    }
  }
]
