import { csrf } from 'src/lib/csrf';
import { Auth } from './model';

async function checkSession(req) {
  try {
    let { session } = req.headers;
    console.log({ session });

    const user_session_found = await Auth.findOne({ where: { session } });

    if (user_session_found) {
      return { status: 'OK', username: user_session_found['dataValues'].username, role: user_session_found.role };
    }
    return { status: 'ERROR SESSION NOT FOUND' };
  } catch (error) {
    console.error(error);
    return { status: 'ERROR SESSION NOT FOUND' };
  }
}

async function handler(req, res) {
  try {
    let result = await checkSession(req);

    return res.status(200).send(result);
  } catch (err) {
    console.log(err);
    res.status(200).send({ status: 'error', message: 'checkSession error' });
  }
}

export default csrf(handler);
