function uid() {
  return Math.random().toString(36).slice(2, 10);
}

async function logActivity(pool, action, entity, entityId, extra = '', snapshot = null) {
  const id = uid();
  await pool.query(
    'INSERT INTO activity_log (id, action, entity, entity_id, extra, snapshot, restorable, restored) VALUES (?, ?, ?, ?, ?, ?, ?, 0)',
    [id, action, entity, entityId || '', extra, snapshot, snapshot ? 1 : 0]
  );
  return id;
}

let orderCounter = null;

async function nextOrderId(pool) {
  if (orderCounter === null) {
    const [rows] = await pool.query("SELECT id FROM orders ORDER BY id DESC LIMIT 1");
    if (rows.length > 0) {
      const num = parseInt(rows[0].id.replace('O-', ''), 10);
      orderCounter = num;
    } else {
      orderCounter = 0;
    }
  }
  orderCounter++;
  return `O-${String(orderCounter).padStart(3, '0')}`;
}

module.exports = { uid, logActivity, nextOrderId };
