const { body, param, validationResult } = require('express-validator')
const { checkValidations } = require('../plugins/controllersHelperFunctions')
const InstalledDevice = require('../models/GPS.InstalledDevice')
// const Device = require('../models/GPS.Device')
const userGPS = require('../models/GPS.User')
const Settings = require('../models/GPS.Settings')
const Score = require('../models/GPS.Score')
const { _sr } = require('../plugins/serverResponses')
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
const { findDeviceByImeiOnKoja } = require('../kojaWebService')

module.exports.deviceRegistration = [
  [body('IMEI').notEmpty().isString().withMessage('لطفا IMEI را وارد یا تصحیح کنید')],
  checkValidations(validationResult),
  async (req, res) => {
    const IMEI = req.body.IMEI
    console.log('IMEI ******************', IMEI)

    const existingInstalledDevice = await InstalledDevice.findOne({ IMEI, status: 1 }).catch(err => {
      console.log('err in findOne InstalledDevice', err?.message)
      return res.status(500).json({ msg: 'خطا در دریافت اطلاعات از دیتابیس ثبت دستگاه' })
    })
    if (existingInstalledDevice) {
      return res.status(400).json({ msg: 'این IMEI قبلا ثبت شده ' })
    }
    // const isRegisteredOnKoja = true
    let registeredDevice
    try {
      registeredDevice = await findDeviceByImeiOnKoja(IMEI)
    } catch (err) {
      return res.status(err.status || 500).json({ msg: err.message })
    }
    if (!registeredDevice) {
      return res.status(400).json({ msg: 'هنوز در سامانه ردیاب ثبت نشده است.' })
    }
    if (!registeredDevice.device_type || !registeredDevice.device_type.name) {
      return res.status(400).json({ msg: 'اطلاعات دستگاه ناقص است' })
    }
    let installedDeviceId = null
    let scoreData = null
    let walletUpdated = false
    try {
      const fee = await Settings.findOne({ title: 'install_fee' })
      if (!fee) {
        return res.status(400).json({ msg: 'هزینه نصب یافت نشد' })
      }
      const score = await Settings.findOne({ title: 'install_score' })
      if (!score) {
        return res.status(400).json({ msg: 'امتیاز نصب یافت نشد' })
      }
      const data = {
        // deviceId: RegisteredDevice.deviceId,
        installationDate: new Date(registeredDevice.activated_at),
        deviceType: convertModel(registeredDevice.device_type.name),
        status: 1,
        registerDate: new Date(),
        userId: req.user_id,
        IMEI: req.body.IMEI,
        profit: fee.amount,
        score: score.amount
      }
      // 1.add to installed device
      const installedDevice = await InstalledDevice.create(data)
      installedDeviceId = installedDevice._id
      // 2. add to score
      scoreData = await Score.create({
        title: 'ثبت دستگاه',
        deviceId: installedDevice.id,
        score: score.amount,
        userId: req.user_id
      })

      // 3. add to wallet
      await userGPS.findByIdAndUpdate(req.user_id, {
        $inc: { walletBalance: fee.amount, score: score.amount, totalScore: score.amount }
      })
      walletUpdated = true

      notifyAdmin('newInstallDeviceRequest')
      res.status(201).json({
        msg:
          'مبلغ ' + fee.amount + ' تومان به کیف پول شما اضافه شد و ' + score.amount + ' امتیاز به امتیاز شما اضافه شد'
      })
    } catch (err) {
      console.log('Error in Db Transactions', err?.message)
      if (installedDeviceId) {
        try {
          await InstalledDevice.deleteOne({ _id: installedDeviceId })
          console.log('Rollback: InstalledDevice deleted.')
        } catch (error) {
          console.error('CRITICAL: Rollback failed for some changes. MANUAL INTERVENTION REQUIRED.', error)
        }
      }
      if (scoreData) {
        try {
          await Score.deleteOne({ _id: scoreData._id })
          console.log('Rollback: Score deleted.')
        } catch (error) {
          console.error('CRITICAL: Rollback failed for some changes. MANUAL INTERVENTION REQUIRED.', error)
        }
      }
      if (walletUpdated) {
        try {
          const fee = await Settings.findOne({ title: 'install_fee' })
          const score = await Settings.findOne({ title: 'install_score' })
          if (fee && score) {
            await userGPS.findByIdAndUpdate(req.user_id, { $inc: { walletBalance: -fee.amount, score: -score.amount } })
            console.log('Rollback: Wallet balance and score reverted.')
          }
        } catch (error) {
          console.error('CRITICAL: Rollback failed for wallet update. MANUAL INTERVENTION REQUIRED.', error)
        }
      }
      return res.status(err?.status || 500).json({ msg: err?.msg || 'خطا در تراکنش های دیتابیس ' })
    }

    // console.log('deviceRegistration Error: ', err?.message)
    // if (err.response) {
    //   const { status } = err.response
    //   return res.status(status || 500).json({ msg: err.message || 'خطا!' })
    // }
  }
]

module.exports.getAllForUser = 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 InstalledDevice.find(filter).skip(page).limit(rows).sort(sort).populate('deviceId')

    const total = await InstalledDevice.countDocuments(filter)

    res.status(200).json({ data, total })
  } catch (error) {
    res.status(500).json({ message: 'An error occurred', 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 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 InstalledDevice.find()
      .sort({ created_at: -1 })
      .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 })
  }
}

module.exports.updateInstalled = [
  [
    param('id').notEmpty().isMongoId().withMessage('لطفا ایدی را وارد یا تصحیح کنید'),
    param('type').notEmpty().isString().withMessage('لطفا وضعیت را وارد یا تصحیح کنید')
  ],
  checkValidations(validationResult),
  async (req, res) => {
    try {
      console.log('updateInstalled ******************', req.params.id, req.params.type)
      const installedDevice = await InstalledDevice.findById(req.params.id)
      if (!installedDevice) {
        return res.status(404).json({ msg: 'این ایدی وجود ندارد' })
      }
      console.log('installedDevice ******************')
      // const user = await User.findById(installedDevice.userId).select('walletBalance score totalScore')
      switch (req.params.type) {
        // case 'accept': {
        //   installedDevice.status = 1
        //   installedDevice.installationDate = new Date()
        //   // device.status = 1

        //   // user.walletBalance += device.profit
        //   // user.dollarBalance += device.dollarProfit
        //   // user.totalScore += device.score
        //   // user.score += device.score

        //   await Score.create({
        //     title: 'ثبت دستگاه',
        //     deviceId: device.id,
        //     score: device.score,
        //     userId: installedDevice.userId
        //   })
        //   user.save()
        //   device.save()
        //   installedDevice.save()
        //   notifyAdmin('newInstallDeviceRequest')

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

        //   break
        // }
        case 'reject': {
          console.log('reject ******************')
          installedDevice.status = 2
          await installedDevice.save()
          console.log('installedDevice saved ******************')

          // Get fee and score from Settings (same as during registration)
          const fee = await Settings.findOne({ title: 'install_fee' })
          const score = await Settings.findOne({ title: 'install_score' })

          if (fee && score) {
            // remove from wallet
            await userGPS.findByIdAndUpdate(installedDevice.userId, {
              $inc: {
                walletBalance: -fee.amount,
                score: -score.amount,
                totalScore: -score.amount
              }
            })
            console.log('userGPS updated ******************')
          }

          await Score.deleteMany({ deviceId: installedDevice.id })
          console.log('Score deleted ******************')

          notifyAdmin('newInstallDeviceRequest', installedDevice.userId)
          res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice })

          break
        }
        default: {
          res.status(404).json({ msg: 'وضعیت اشتباه است' })
          break
        }
      }
    } catch (error) {
      console.error('Error in updateInstalled:', error?.message)
      return res.status(500).json({ msg: 'خطا در به‌روزرسانی وضعیت دستگاه' })
    }
  }
]

function convertModel(model) {
  switch (model.toLowerCase()) {
    case 'gs10g':
      return 'G10'
    case 'concox_x3':
      return 'G11'
    case 'coban_gps303g':
      return 'G12'
    default:
      return model
  }
}
