const db = require("../models");
const API = require('../helper/API_Response');
const db_helper = require("../helper/db_helper");
const helper = require("../helper/helper");
const { Acronyms, Certificate } = require("../models");

exports.get_survey = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var already = await db_helper.selectByWhere("TakeSurvey", {
    user_id: input.user_id,
    cohort_id: input.cohort_id,
  });
  res.status(200).send(API._200(await already));
};
exports.survey_domain = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const result = await db.sequelize.query(
    "select id,domin_name from domains where certi_id in(select certi_id from cohorts where id= :cohort_id)",
    { replacements: { cohort_id: input.cohort_id } }
  )
    .then(function (data) {
      return Array.from(new Set(data));
    });
  res.status(200).send(API._200(await result));
};
exports.take_survey = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  var already = await db_helper.selectByWhere("TakeSurvey", {
    user_id: input.user_id,
    cohort_id: input.cohort_id,
  });
  if (already.length <= 0)
    res.status(200).send(API._200(await db_helper.addData("TakeSurvey", input)));
  else {
    input.id = already[0].id;
    res.status(200).send(API._200(await db_helper.update("TakeSurvey", input)));
  }
};
exports.add = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.addData('Acronyms', input)));
};
exports.all = async (req, res) => {
  const all = await Acronyms.findAll({
    where: {
      status: 0,
    },
    include: [{
      model: Certificate,
      attributes: ["id", "certificate_name"],
    },
    ],
  });
  res.status(200).send(API._200(await all));
};
exports.byid = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.byId('Acronyms', input.id)));
};
exports.delete = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.statusChange('Acronyms', input.id)));

};
exports.update = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  res.status(200).send(API._200(await db_helper.update('Acronyms', input)));
};
