import { Order, sequelize } from './model';
import { Auth } from '../auth/model';

async function list(req) {
  try {
    let session = req.headers['session'];
    console.log(session);

    const checkIfAdmin = user => user['dataValues'].role == 'admin';

    await sequelize.authenticate();

    const user = await Auth.findOne({ where: { session } });
    console.log(user);
    if (checkIfAdmin(user)) {
      const orders = await Order.findAll();

      return { status: 'OK', orders };
    } else {
      return { status: 'ERROR', msg: 'Permission denied', orders: [] };
    }
  } catch (error) {
    console.error(error);
  }
}

export default async function handler(req, res) {
  try {
    let result = await list(req);

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