import { Order, sequelize } from './model';
import formidable from 'formidable';
var randomize = require('randomatic');
import rimraf from 'fs-extra';
const path = require('path');
const fs = require('fs');

import crypto from 'crypto';
import { Auth } from '../auth/model';
import { Product } from '../products/model';
import { csrf } from 'src/lib/csrf';

function genSalt() {
  return crypto.randomBytes(16).toString('hex');
}

function createMD5HashWithSalt(inputString, salt) {
  // Prepend the salt to the inputString
  const saltedInput = salt + inputString;

  // Proceed with the MD5 hash
  const hash = crypto.createHash('md5').update(saltedInput).digest('hex');

  // Optionally, you might want to return both the hash and the salt
  // for storage, so you can verify the input against the hash later.
  return { salt, hash };
}

async function GetOrderDetails(req) {
  try {
    let { cart, currency_code } = req.body;
    let { session } = req.headers;

    await sequelize.authenticate();
    let user_found = await Auth.findOne({ where: { session } });

    let items = [];
    for (let i = 0; i < cart.length; i++) {
      let cart_item = cart[i];
      let product_found = await Product.findOne({ where: { pid: cart_item.pid } });
      items.push({
        item_name: product_found['dataValues'].name,
        currency_code: currency_code,
        unit_price: product_found['dataValues'].price,
        quantity: cart_item.quantity,
      });
    }

    //get total price from cart
    let total_price = cart.reduce((acc, ci) => acc + ci.quantity * ci.unit_price, 0);
    let amount = cart.reduce((acc, ci) => acc + ci.quantity * ci.unit_price, 0);

    let salt = genSalt();
    let req_digest = createMD5HashWithSalt(
      {
        order_status: 'ORDER_SUBMITTED',
        invoice_id: crypto.randomUUID(),
        items: JSON.stringify(items),
        username: user_found.username,
        total_price: total_price,
        currency_code: currency_code,
        amount: amount,
      },
      salt,
    )['hash'];

    await Order.create({
      order_status: 'ORDER_SUBMITTED',
      invoice_id: crypto.randomUUID(),
      items: JSON.stringify(items),
      username: user_found.username,
      custom_id: req_digest,
      total_price,
      currency_code,
      amount: amount,
      salt,
    });

    return { status: 'OK', order_details: { custom_id: req_digest } };
  } catch (error) {
    console.error(error);
  }
}

async function handler(req, res) {
  try {
    let result = await GetOrderDetails(req);

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

export default csrf(handler);
