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

exports.topicGetById = async (req, res) => {
  const topicId = await helper.decryptUri(req.params.id)
  const topic = await Topic.findOne({
    where: {
      id: topicId,
      status: 0
    }
  });
  if (!topic) {
    res.status(404).send(API._404({ message: `topic with id: ${id} was not found` }));
  }
  res.status(200).send(API._200(await topic));
};
exports.deleteTopic = async (req, res) => {
  const topicId = await helper.decryptUri(req.params.id)
  const topic = await Topic.findByPk(topicId).then(async res1 => {
    res1.set("status", 1);
    return await res1.save();
  })
  res.status(200).send(API._200(await topic));
};
exports.updateTopic = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const topic = await Topic.findByPk(id)
  if (!topic) {
    res.status(404).send(API._404({ message: `topic with id: ${id} was not found` }));
  }
  if (input.topic_name) topic.topic_name = input.topic_name;
  if (input.d_id) topic.d_id = input.d_id;
  if (input.sd_id) topic.sd_id = input.sd_id;
  if (input.status) topic.status = input.status;
  if (input.certi_id) topic.certi_id = input.certi_id;
  if (input.cource_id) topic.cource_id = input.cource_id;
  if (input.description) topic.description = input.description;
  if (input.video_url) topic.video_url = input.video_url;
  if (input.topic_number) topic.topic_number = input.topic_number;
  if (input.sr_number) topic.sr_number = input.sr_number;

  res.status(200).send(API._200(await topic.save()));
};
exports.getAllTopic = async (req, res) => {
  const topic = Topic.findAll({
    where: {
      status: 0
    },
    include: [{
      model: Domain,
      attributes: ['id', 'domin_name']
    }, {
      model: Subdomain,
      attributes: ['id', 'subdomain_name']
    }, {
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }, {
      model: Cource,
      attributes: ['id', 'course_name']
    }]
  });
  res.status(200).send(API._200(await topic));
};
exports.addTopic = async (req, res) => {
  const data = await helper.decryptRequest(req.body.data);
  const topic = await Topic.create(data);
  res.status(200).send(API._200(await topic));
};