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

async function view(req) {
  let { pid } = req.query;

  await sequelize.authenticate();

  const product = await Product.findOne({ where: { pid } });
  if (product) {
    let product_count = await Item.count({ where: { pid, sold: false } });
    product.dataValues['count'] = product_count;

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

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

    return { status: 'OK', product, product_count };
  } else {
    throw new Error('PID_NOT_FOUND');
  }
}

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

    return res.status(200).send(result);
  } catch (err) {
    if (err.message === 'PID_NOT_FOUND') {
      // res redirect to '/'
      res.redirect(302, '/');

      return;
    }

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