const bcrypt = require("bcryptjs");
const _ = require("lodash");
const express = require("express");
const { CompanyUsers } = require("../../models/CompanyUsers");
const router = express.Router();
const mongoose = require("mongoose");

module.exports.add = async (req, res) => {
  try {
    let record = req.body;

    let user = await CompanyUsers.findOne({
      email: record.email,
      company: record.company,
    });

    if (user) throw Error("User already registered this email.");
    user = new CompanyUsers(record);
    const salt = await bcrypt.genSalt(10);
    user.password = await bcrypt.hash(user.password, salt);
    user = await user.save();
    return res.status(200).send(user);
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.changePassword = async (req, res) => {
  try {
    let record = await CompanyUsers.findById(req.body.id);
    if (!record) throw Error("The record with the given ID was not found.");
    const salt = await bcrypt.genSalt(10);
    record.password = await bcrypt.hash(req.body.password, salt);
    record = await record.save();
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.getSingle = async (req, res) => {
  try {
    console.log("req.params.id", req.params.id);
    const record = await CompanyUsers.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.delete = async (req, res) => {
  try {
    const record = await CompanyUsers.findByIdAndRemove(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.multipleDelete = async (req, res) => {
  try {
    console.log();
    let { deleteItems } = req.body;
    const objectIdArray = deleteItems.map((id) => mongoose.Types.ObjectId(id));
    await CompanyUsers.deleteMany({
      _id: { $in: objectIdArray },
    });

    return res.send({ message: "deleted" });
  } catch (err) {
    console.error(err);
    return res.status(404).send({ error: err.message });
  }
};

module.exports.update = async (req, res) => {
  try {
    console.log("REQ BODY:", req.body);
    let record = await CompanyUsers.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");

    record = await CompanyUsers.findByIdAndUpdate(req.params.id, req.body);
    res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.all = async (req, res) => {
  try {
    let drivers = await CompanyUsers.find({});
    return res.status(200).send(drivers);
  } catch (err) {
    console.log(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.query = async (req, res) => {
  try {
    let query = req.body.query;
    query = query ? query : {};
    query.page = query.page ? query.page : 0;
    query.pageSize = query.pageSize ? query.pageSize : 10;
    let conditions = {};
    if (query.search) {
      conditions.$and = [
        {
          $or: [{ name: { $regex: new RegExp(query.search, "i") } }],
        },
      ];
    }
    let skip = query.page * query.pageSize;
    let sort = {};
    if (query.orderBy) {
      sort[query.orderBy.field] = query.orderDirection == "asc" ? 1 : -1;
    }
    const records = await CompanyUsers.find(conditions)
      .skip(skip)
      .sort(sort)
      .limit(query.pageSize)
      .populate("company", "name");

    let total = await CompanyUsers.countDocuments(conditions);
    // total = Math.ceil(total / query.pageSize);
    res.send({ data: records, page: query.page, total });
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};
