const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { User } = require("../models");
exports.login = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data)
  let email = data.email;
  let password = await helper.getHashedPassword(data.password.toString());
  const user = await User.findOne({ where: { email } });
  if (!user) {
    res.status(200).send(API._200({ message: "User not found", user_status: 404 }));
  }
  const passwordMatch = user.password === password;
  if (!passwordMatch) {
    res.status(200).send(API._200({ message: "Invalid password", user_status: 404 }));
  }
  res.status(200).send(API._200(user));
};
exports.addUser = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data)
  if (data.password) data.password = await helper.getHashedPassword(data.password.toString());
  data.remember_token = helper.generateAuthToken();
  if (data.roll_id == 0) {
    data.roll_id = 3;
    data['allow_access'] = 0;
    data['is_flashcard_user'] = 1;
  }
  if (data.signup_platform && data.signup_platform != '' && data.signup_platform != null) {
    data['allow_access'] = 1;
    data['is_flashcard_user'] = 1;
  }
  var err = [];
  const user = await User.create(data).catch((ex) => {
    err = ex.errors[0]
  });
  if (err.message)
    res.status(409).send(API._404({ message: err.message }));
  else
    res.status(200).send(API._200(user));
};

exports.findAll = (req, res) => {
  User.findAll().then(async data => {
    if (!data) {
      res.status(404).send(API._404({ message: "User not found" }));
    }
    let user = [];
    user = data;
    const promises = user.map(async user => {
      const u_cohort = await db_helper.query(`SELECT id, cohort_name FROM cohorts WHERE FIND_IN_SET(${user.id}, userslist)`);
      user['cohort'] = u_cohort[0];
      return user;
    });
    const updatedUsers = await Promise.all(promises);
    console.log(updatedUsers)
    res.status(200).send(API._200(updatedUsers));
  })

};

// Find a single User with an id
exports.findOne = async (req, res) => {
  const ids = req.params.id;
  const id = await helper.decryptUri(ids)
  User.findByPk(id)
    .then(data => {
      if (data) {
        res.send(data);
      } else {
        res.status(404).send({
          message: `Cannot find User with id=${id}.`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving User with id=" + id
      });
    });
};

// Update a User by the id in the request
exports.updateUser = async (req, res) => {
  debugger
  const id = await helper.decryptUri(req.params.id);
  const input = await helper.decryptRequest(req.body.data)
  // const user = await User.findByPk(await helper.decryptUri(event.pathParameters.id))
  const user = await User.findByPk(id)
  if (!user) {
    res.status(404).send(API._404({ message: `User with id: ${id} not found` }));
  }
  if (input.name) user.name = input.name;
  if (input.email) user.email = input.email;
  if (input.roll_id) user.roll_id = input.roll_id;
  if (input.permissions) user.permissions = input.permissions;
  if (input.email_verified_at) user.email_verified_at = input.email_verified_at;
  if (input.email_verified) user.email_verified = input.email_verified;
  if (input.free_flashcard) user.free_flashcard = input.free_flashcard;
  if (input.free_practque) user.free_practque = input.free_practque;
  if (input.free_flashccsp) user.free_flashccsp = input.free_flashccsp;
  if (input.pass_rest_code) user.pass_rest_code = input.pass_rest_code;
  if (input.calling_code) user.calling_code = input.calling_code;
  if (input.avatar_url) user.avatar_url = input.avatar_url;
  if (input.is_first) user.is_first = input.is_first;
  if (input.aliasname) user.aliasname = input.aliasname;
  if (input.opt_in) user.opt_in = input.opt_in;
  if (input.company_id) user.company_id = input.company_id;
  if (input.address) user.address = input.address;
  if (input.notes) user.notes = input.notes;
  if (input.schedule_date) user.schedule_date = input.schedule_date;
  if (input.allow_access) user.allow_access = input.allow_access;
  if (input.authy_id) user.authy_id = input.authy_id;
  if (input.mobile) user.mobile = input.mobile;
  if (input.user_time_zone) user.user_time_zone = input.user_time_zone;
  if (input.is_selfpaced) user.is_selfpaced = input.is_selfpaced;
  if (input.mentor_id) user.mentor_id = input.mentor_id;
  if (input.mentor_notes) user.mentor_notes = input.mentor_notes;

  user.remember_token = helper.generateAuthToken();
  if (input.password) user.password = helper.getHashedPassword(input.password);

  res.status(200).send(API._200(await user.save()));
};

// Delete a User with the specified id in the request
exports.delete = async (req, res) => {
  const userId = await helper.decryptRequest(req.params.id)
  const sql = ["DELETE FROM `notes` WHERE `user_id` = " + userId,
  "DELETE FROM `enrollusers` WHERE `u_id` = " + userId,
  "DELETE FROM `flash_card_ans` WHERE `user_id` = " + userId,
  "DELETE FROM `flashans_offlines` WHERE `UserId` = " + userId,
  "DELETE FROM `flashcard_offlines` WHERE `UserId` = " + userId,
  "DELETE FROM `discussions` WHERE `u_id` = " + userId,
  "DELETE FROM `ketexam_ans` WHERE `user_id` = " + userId,
  "DELETE FROM `know_ass_ques_ans` WHERE `user_id` = " + userId,
  "DELETE FROM `practice_ans` WHERE `user_id` = " + userId,
  "DELETE FROM `flashapp_syncs` WHERE `UserId` = " + userId,
  "DELETE FROM `results` WHERE `user_id` = " + userId,
  "DELETE FROM `study_mat_feedbacks` WHERE `user_id` = " + userId,
  "DELETE FROM `schedules` WHERE `user_id` = " + userId,
  "DELETE FROM `livequestion_ans` WHERE `user_id` = " + userId,
  "DELETE FROM `login_logs` WHERE `user_id` = " + userId,
  "DELETE FROM `user_logs` WHERE `user_id` = " + userId,
  "DELETE FROM `test_logs` WHERE `user_id` = " + userId,
  "DELETE FROM `teacher_accesses` WHERE `user_id` = " + userId,
  "DELETE FROM `quedb_updates` WHERE `user_id` = " + userId,
  "DELETE FROM `app_supports` WHERE `user_id` = " + userId,
  "DELETE FROM `question_discussions` WHERE `user_id` = " + userId,
  "DELETE FROM `notifications` WHERE `user_id` = " + userId,
  "DELETE FROM `notification_settings` WHERE `user_id` = " + userId,
  "DELETE FROM `chattings` WHERE `user_id` = " + userId,
  "DELETE FROM `meeting_chats` WHERE `user_id` = " + userId,
  "DELETE FROM `payment_transactions` WHERE `user_id` = " + userId,
  "DELETE FROM `activity_trackers` WHERE `user_id` = " + userId,
  "DELETE from activity_trackers where email in(select email from users where id=" + userId + ")",
  "DELETE FROM `users` WHERE `id` = " + userId];
  // const user = await db.sequelize.query(sql)
  const user = await Promise.all(sql.map(query => db.sequelize.query(query)));

  if (!user) {
    res.status(404).send(API._404({ message: `User with id: ${userId} not found` }));
  }
  res.status(200).send(API._200(user));

};


// Find a single User with an id
exports.filterUser = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data)
  const user = await User.findOne({
    where: data
  });
  if (!user) {
    res.status(404).send(API._404({ message: `User was not found` }));
  }

  res.status(200).send(API._200(user));
};


exports.verifyEmailOtp = async (req, res) => {
  console.log("------------call---------------")
  const input = req.body
  const user = await User.findOne({
    where: { email: input.email, email_otp: input.otp }
  });
  if (user) {
    user.password = await helper.getHashedPassword(input.password.toString());
    user.email_otp = null;
    user.email_verified_at = new Date().toISOString()
    user.email_verified = "true"
    res.status(200).send(API._200(await user.save()));
  } else {
    res.status(400).send(API._400({ message: "Invalid otp" }));
  }
};