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

async function check_out(req) {
  let t;

  try {
    let cart_items = req.body;

    //   // create sequelize transaction
    t = await sequelize.transaction();
    await sequelize.authenticate();

    for (let i = 0; i < cart_items.length; i++) {
      let cart_item = cart_items[i];
      let { pid, quantity } = cart_item;

      let item_remaining = Item.count({ where: { pid, sold: false } }, { transaction: t });
      if (quantity > item_remaining) {
        throw new Error('error due to ordered quantity is greater than item remaining');
      } else {
        console.log('remaining check passed');
      }
    }

    // item remaining check passed
    // proceed to mark item sold
    for (let i = 0; i < cart_items.length; i++) {
      let cart_item = cart_items[i];
      let { pid, quantity } = cart_item;
      for (let j = 1; j <= quantity; j++) {
        let item;

        item = await Item.findOne({ where: { pid, sold: false } }, { transaction: t });
        await Item.update({ sold: true }, { where: { item_id: item.item_id } }, { transaction: t });
        console.log(item.item_id);
      }
    }

    await t.commit();

    //   return { status: 'OK', message: 'checkout done' };
  } catch (error) {
    await t?.rollback();

    console.error(error);
    return { status: 'ERROR', message: 'cart checkout error' };
  }
}

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

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

export const config = {
  api: {
    bodyParser: true,
  },
};
