import { promise } from 'bcrypt/promises';
import { Item } from '../inventory/model';
import { Product, sequelize } from './model';

async function listByCategory(req) {
  try {
    await sequelize.authenticate();
    let { cid } = req.query;

    const products = await Product.findAll({ where: { cid } });
    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);
  }
}

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

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