const { uploadFiles, moveFiles, deleteFiles } = require('../../controllers/files/files');
const { errorHandler } = require('../../util');

const router = require('express').Router();
const jwt = require('jsonwebtoken');

const authMiddleware = async (req, res, next) => {
	try {
		const authHeader = req.get('Authorization');
		if (!authHeader) {
			return errorHandler('Not authenticated', 401);
		}

		const token = authHeader.split(' ')[1];
		let decodedToken;

		const secretKeys = [process.env.SECRET_KEY, process.env.CONVENTION_SECRET_KEY, process.env.DRIVER_SECRET_KEY];

		for (const key of secretKeys) {
			try {
				decodedToken = jwt.verify(token, key);
				break;
			} catch (e) {}
		}

		if (!decodedToken) {
			return errorHandler('Not Authenticated', 401);
		}

		next();
	} catch (err) {
		console.error(err);
		next(err);
	}
};

const apiKeyMiddleware = (req, res, next) => {
	const apiKey = req.get('x-api-key');
	const validApiKeys = process.env.FILES_API_KEY;

	if (!apiKey || apiKey !== validApiKeys) {
		return res.status(403).json({ success: false, message: 'Forbidden: Invalid API key' });
	}

	next();
};

router.post('/', authMiddleware, uploadFiles);
router.patch('/', apiKeyMiddleware, moveFiles);
router.delete('/', apiKeyMiddleware, deleteFiles);

module.exports = router;
