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

exports.domainGetById = async (req, res) => {
  const domainId = await helper.decryptUri(req.params.id)
  const domain = await Domain.findOne({
    where: {
      id: domainId,
      status: 0,
    }
  });
  if (!domain) {
    res.status(404).send(API._404({ message: `Domain with id: ${domainId} was not found` }));
  }
  res.status(200).send(API._200(await domain));
};
exports.deleteDomain = async (req, res) => {
  const domainId = await helper.decryptUri(req.params.id)
  var sql = `Update domains set status=1 where id=${domainId}; ` +
    `Update subdomains set status=1 where d_id=${domainId};` +
    `Delete from flash_card_ans where d_id=${domainId}; ` +
    `Delete from flashans_offlines where domain=${domainId}; ` +
    `Delete from flashcard_offlines where domain=${domainId}; ` +
    `Update flashcards set status=1 where d_id=${domainId}; ` +
    `Update ketexamques set status=1 where d_id=${domainId}; ` +
    `Update know_ass_ques set status=1 where d_id=${domainId}; ` +
    `Delete from notes where domain_id=${domainId}; ` +
    `Update practice_appques set status=1 where d_id=${domainId}; ` +
    `Update practiceques set status=1 where d_id=${domainId}; ` +
    `Delete from results where domain_id=${domainId}; ` +
    `Update study_materials set status=1 where d_id=${domainId}; ` +
    `Update topics set status=1 where d_id=${domainId}; `;
  const domain = await db.sequelize.query(sql)
  res.status(200).send(API._200(await domain));
};
exports.updateDomain = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const domain = await Domain.findByPk(id)
  if (!domain) {
    res.status(404).send(API._404({ message: `Domain with id: ${id} was not found` }));
  }
  if (input.domin_name) domain.domin_name = input.domin_name
  if (input.certi_id) domain.certi_id = input.certi_id
  if (input.cource_id) domain.cource_id = input.cource_id
  if (input.domain_number) domain.domain_number = input.domain_number
  if (input.status) domain.status = input.status
  res.status(200).send(API._200(await domain.save()));
};

exports.getAllDomain = async (req, res) => {
  const domain = Domain.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }, {
      model: Cource,
      attributes: ['id', 'course_name']
    }]
  });
  res.status(200).send(API._200(await domain));
};
exports.addDomain = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  var err = [];
  const domain = await Domain.create(data).catch((ex) => err = ex.errors[0]);
  if (err.length > 0) {
    res.status(400).send(API._400({ message: err.message }));
  }
  res.status(200).send(API._200(await domain));
};