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.certificateGetById = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const certificate = await Certificate.findOne({
    where: {
      id: id,
      status: 0,
    },
  });
  if (!certificate) {
    res.status(404).send(API._404({ message: `Certificate with id: ${id} was not found` }));
  }
  res.status(200).send(API._200(await certificate));
};
exports.deleteCertificate = async (req, res) => {
  const id = await helper.decryptUri(req.params.id)
  const certificate = await Certificate.findByPk(id)
  if (!certificate) {
    res.status(404).send(API._404({ message: `Certificate with id: ${id} was not found` }));
  }
  certificate.status = 1
  await db_helper.query("delete from cohorts where certi_id=" + id);
  await db_helper.query("delete from self_paced_one_times where certi_id=" + id);
  await db_helper.query("delete from self_paced_subscriptions where certi_id=" + id);
  await db_helper.query("delete from self_paceds where certi_id=" + id);

  res.status(200).send(API._200(await certificate.save()));
};
exports.updateCertificate = async (req, res) => {
  const input = await helper.decryptRequest(req.body.data);
  const id = await helper.decryptUri(req.params.id)
  const certificate = await Certificate.findByPk(id)
  if (!certificate) {
    res.status(404).send(API._404({ message: `Certificate with id: ${id} was not found` }));
  }
  if (input.certificate_name) certificate.certificate_name = input.certificate_name
  if (input.status) certificate.status = input.status;
  if (input.days) certificate.days = input.days
  if (input.short_name) certificate.short_name = input.short_name
  if (input.description) certificate.description = input.description
  if (input.access) certificate.access = input.access
  if (input.pass_guarantee) certificate.pass_guarantee = input.pass_guarantee
  if (input.fee) certificate.fee = input.fee
  if (input.status) certificate.status = input.status
  if (input.img_path) certificate.img_path = input.img_path
  if (input.logo_path) certificate.logo_path = input.logo_path

  if (input.img_path) {
    certificate.img_path = await helper.uploadFile(input.img_path);
  }

  if (input.logo_path) {
    certificate.logo_path = await helper.uploadFile(input.logo_path);
  }
  res.status(200).send(API._200(await certificate.save()));
};
exports.getAllCertificate = async (req, res) => {
  const certificate = Certificate.findAll({
    where: {
      status: 0
    }
  });
  res.status(200).send(API._200(await certificate));
};