const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const { Members } = require('../models');

dotenv.config();

async function optionalAuth(req) {
	try {
		const authHeader = req.get('Authorization');
		if (!authHeader) {
			return null;
		}

		const token = authHeader.split(' ')[1];
		let decodedToken;
		try {
			decodedToken = jwt.verify(token, process.env.SECRET_KEY);
		} catch (err) {
			return null;
		}

		if (!decodedToken) {
			return null;
		}

		const member = await Members.findByPk(decodedToken.memberId);

		if (!member) {
			return null;
		}

		return member.get({ plain: true });
	} catch (err) {
		return null;
	}
}
module.exports = { optionalAuth };
