import { csrf } from 'src/lib/csrf';
import { Item } from '../inventory/model';
import { Product, sequelize } from './model';

async function list(req) {
  try {
    await sequelize.authenticate();

    const products = await Product.findAll();
    for (var i = 0; i < products.length; i++) {
      let product_data = products[i].dataValues;
      let { pid } = product_data;

      let product_count = await Item.count({ where: { pid } });
      products[i].dataValues['count'] = product_count;

      let product_unsold_count = await Item.count({ where: { pid, sold: false } });
      products[i].dataValues['unsold_count'] = product_unsold_count;

      let product_sold_count = await Item.count({ where: { pid, sold: true } });
      products[i].dataValues['sold_count'] = product_sold_count;
    }

    return { status: 'OK', products };
  } catch (error) {
    console.error(error);
  }
}

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' });
  }
}

export default csrf(handler);
