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

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

    await sequelize.authenticate();

    let user = await Auth.findOne({ where: { session } });

    if (user) {
      const { username } = user['dataValues'];
      console.log({ username });

      const orders = await Order.findAll({ where: { username } });

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

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

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