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

module.exports.add = async (req, res) => {
  try {
    // console.log("REQ BODY:", req.body);
    let record = req.body;
    let user = new Questions(record);
    user = await user.save();
    return res.status(200).send("OK");
  } catch (err) {
    console.error(err);
    return res.status(400).send({ error: err.message });
  }
};

module.exports.getSingle = async (req, res) => {
  try {
    // console.log("QUESTION SINGLE REQ PARAMS: ", req.params);
    const record = await Questions.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(401).send({ error: err.message });
  }
};

module.exports.getSingleFR = async (req, res) => {
  try {
    // console.log("QUESTION SINGLE REQ PARAMS: ", req.params);
    const record = await Questions.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(401).send({ error: err.message });
  }
};

module.exports.delete = async (req, res) => {
  try {
    const record = await Questions.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(401).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 Questions.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 {
    let record = await Questions.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");

    record = await Questions.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 Questions.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") } }],
        },
      ];
    }

    if (query.filter !== "all") {
      conditions = {
        ...conditions,
        company: { $eq: query.filter },
      };
    }

    let skip = query.page * query.pageSize;
    let sort = {};
    if (query.orderBy) {
      sort[query.orderBy.field] = query.orderDirection == "asc" ? 1 : -1;
    }
    const records = await Questions.find(conditions)
      .skip(skip)
      .sort(sort)
      .limit(query.pageSize)
      .populate("company");

    let total = await Questions.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 });
  }
};

module.exports.getCompanyQuestions = async (req, res) => {
  try {
    const { companyId } = req.body;
    const record = await Questions.find({ company: companyId });
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(401).send({ error: err.message });
  }
};

module.exports.getFirstQuestion = async (req, res) => {
  try {
    // console.log("FIRST QUESTION REQ BODY: ", req.body);
    const { companyId } = req.body;
    const record = await Questions.findOne({
      company: companyId,
      firstQuestion: true,
    });
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(401).send({ error: err.message });
  }
};

module.exports.getFirstQuestionFR = async (req, res) => {
  try {
    // console.log("FIRST QUESTION REQ BODY: ", req.company);
    const record = await Questions.findOne({
      company: req.body?.companyId,
      firstQuestion: true,
    });
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(401).send({ error: err.message });
  }
};

module.exports.markAsFirst = async (req, res) => {
  try {
    const { questionId, firstQuestion, companyId } = req.body;
    let record = await Questions.findById(questionId);
    if (!record)
      return res
        .status(401)
        .send({ error: "The record with the given ID was not found." });

    record = await Questions.findByIdAndUpdate(questionId, {
      $set: {
        firstQuestion: firstQuestion,
      },
    });
    if (req.body.firstQuestion) {
      await Questions.updateMany(
        { default: true, _id: { $ne: record._id }, company: companyId },
        {
          $set: {
            firstQuestion: false,
          },
        }
      );
    }
    return res.send(record);
  } catch (err) {
    console.error(err);
    return res.status(401).send({ error: err.message });
  }
};
