require('dotenv').config();
const jwt = require('jsonwebtoken');
const responses = require('../helpers/responses');
const db = require('../../models/migration');
const User = db.User;

const authentication = async (req, res, next) => {
    try {
        const header = req.header('Authorization');
        if (!header) {
            return responses.failed(res, 401);
        }

        const idToken = header.replace('Bearer ', '');
        const decoded = jwt.verify(idToken, process.env.JWT_SECRET_KEY);

        const userId = decoded.id;
        const user = await User.findByPk(userId);

        if (!user) {
            return responses.failed(res, 401);
        }
        if (user.is_suspended) {
            return responses.failed(res, 403, 'Akun Anda telah ditangguhkan');
        }

        req.user = user;
        return next();
    } catch (e) {
        console.error(e);
        return responses.failed(res, 401);
    }
};

module.exports = authentication;
