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

exports.subDomainGetById = async (req, res) => {
  const subdomainId = await helper.decryptUri(req.params.id)
  const subdomain = await Subdomain.findOne({
    where: {
      id: subdomainId,
      status: 0
    },
    include: [{
      model: Domain,
      attributes: ['id', 'domin_name']
    }, {
      model: Certificate,
      attributes: ['id', 'certificate_name']
    }, {
      model: Cource,
      attributes: ['id', 'course_name']
    }]
  });
  if (!subdomain) {
    res.status(404).send(API._404({ message: `subdomain with id: ${id} was not found` }));
  }
  res.status(200).send(API._200(await subdomain));
};
exports.deleteSubDomain = async (req, res) => {
  const subdomainId = await helper.decryptUri(req.params.id)
  const subdomain = await Subdomain.findByPk(subdomainId).then(async res1 => {
    res1.set("status", 1);
    return await res1.save();
  })
  res.status(200).send(API._200(await subdomain));
};
exports.updateSubDomain = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const subdomain = await Subdomain.findByPk(id)
  if (!subdomain) {
    res.status(404).send(API._404({ message: `subdomain with id: ${id} was not found` }));
  }
  if (input.subdomain_name) subdomain.subdomain_name = input.subdomain_name
  if (input.d_id) subdomain.d_id = input.d_id
  if (input.certi_id) subdomain.certi_id = input.certi_id
  if (input.cource_id) subdomain.cource_id = input.cource_id
  if (input.domain_number) subdomain.domain_number = input.domain_number
  if (input.status) subdomain.status = input.status
  if (input.no_assign_note) subdomain.no_assign_note = input.no_assign_note

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