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

module.exports.deviceRegistration = [
    [
        body('IMEI').notEmpty().isString().withMessage('لطفا IMEI را وارد یا تصحیح کنید')
    ],
    checkValidations(validationResult),
    async (req, res) => {
        const device = await Device.findOne({ IMEI: req.body.IMEI });
        if (!device) {
            throw res.status(404).json({ msg: 'این IMEI وجود ندارد' })
            // eslint-disable-next-line eqeqeq
        } else if (device.status == 1) {
            throw res.status(404).json({ msg: 'این IMEI قبلا ثبت شده' })

        } else {
            const data = {
                deviceId: device.id,
                status: 0,
                registerDate: new Date(),
                userId: req.user_id,
                IMEI: req.body.IMEI
            }
            const newRequest = await InstalledDevice.create(data);
            device.status = 1;
            device.save()
            notifyAdmin('newInstallDeviceRequest')

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

        }
    }
]


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(filter)
          .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, totalDocuments, totalPages });
    } 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) => {
        const installedDevice = await InstalledDevice.findById(req.params.id)
        if (!installedDevice) {
            throw res.status(404).json({ msg: 'این ایدی وجود ندارد' })
        } else {
            const user = await User.findById(installedDevice.userId).select('walletBalance dollarBalance score')
            const device = await Device.findById(installedDevice.deviceId)
            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.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": {
                    installedDevice.status = 2;
                    installedDevice.save()
                    device.status = 0;
                    device.save()
                    notifyAdmin('newInstallDeviceRequest')

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


                    break;
                }
                default: {
                    res.status(404).json({ msg: "وضعیت اشتباه است" })
                    break;
                }
            }
        }
    }
]

