/**
 * Internal API Key Generator (Node.js version)
 * Generates a secure internal API key and its bcrypt hash
 */

const crypto = require('crypto');
const bcrypt = require('bcryptjs');

function generateApiKey() {
  const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
  const length = 48;
  let result = "int_shopcall_";

  for (let i = 0; i < length; i++) {
    const randomIndex = crypto.randomInt(0, characters.length);
    result += characters.charAt(randomIndex);
  }

  return result;
}

async function hashApiKey(apiKey) {
  const salt = await bcrypt.genSalt(12);
  return await bcrypt.hash(apiKey, salt);
}

async function main() {
  const keyName = process.argv[2] || "Untitled Internal Key";

  console.log("\n🔑 Generating Internal API Key...\n");

  // Generate API key
  const apiKey = generateApiKey();
  console.log("✅ API Key Generated:");
  console.log(`   ${apiKey}`);

  // Generate hash
  console.log("\n⏳ Generating bcrypt hash...");
  const hash = await hashApiKey(apiKey);
  console.log("✅ Hash Generated:");
  console.log(`   ${hash}`);

  // Output the data
  console.log("\n📝 Data for insertion:");
  console.log("━".repeat(80));
  console.log(JSON.stringify({
    key_name: keyName,
    api_key: apiKey,
    key_hash: hash,
    description: 'Auto-generated internal API key',
    created_by: 'admin'
  }, null, 2));
  console.log("━".repeat(80));
}

main().catch(console.error);
