const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const { errorHandler } = require('../../util');
const { Drivers } = require('../../models');

dotenv.config();

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

		const token = authHeader.split(' ')[1];
		const decodedToken = jwt.verify(token, process.env.DRIVER_SECRET_KEY);

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

		const member = await Drivers.findByPk(decodedToken.driverId);

		if (!member) {
			return errorHandler('Member token not valid.', 401);
		}

		req.driverId = decodedToken.driverId;
		req.userType = decodedToken.userType;

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