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

module.exports.add = async (req, res) => {
  try {
    let record = req.body;
    let user = new Guest(record);
    user.user = req.user?._id;
    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.addFR = async (req, res) => {
  try {
    console.log("REQ BODY: ", req.body);
    let record = req.body;
    let user = new Guest(record);
    user.user = req.user?._id;
    user.company = req.body.companyId;
    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.getSingle = async (req, res) => {
  try {
    const record = await Guest.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 {
    console.log(req.body);
    const record = await Guest.findByIdAndRemove(req.body.id);
    await UserResponses.findOneAndRemove({
      guest: mongoose.Types.ObjectId(req.body?.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.update = async (req, res) => {
  try {
    let record = await Guest.findById(req.params.id);
    if (!record) throw Error("The record with the given ID was not found.");

    record = await Guest.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 Guest.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;
    } else {
      sort.createdAt = -1;
    }
    const records = await Guest.find(conditions)
      .skip(skip)
      .sort(sort)
      .limit(query.pageSize)
      .populate("company", "name");

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