import crypto from 'crypto';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import { ApiKey } from '../src/models';

dotenv.config();

async function generateApiKey(name: string): Promise<void> {
  const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/sportpulse';

  console.log('Connecting to MongoDB...');
  await mongoose.connect(mongoUri);
  console.log('Connected to MongoDB');

  // Generate a random API key
  const apiKey = `sp_${crypto.randomBytes(32).toString('hex')}`;
  const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex');
  const keyPrefix = apiKey.substring(0, 10);

  // Get the next ID
  const lastKey = await ApiKey.findOne().sort({ id: -1 });
  const nextId = lastKey ? lastKey.id + 1 : 1;

  // Create the API key record
  await ApiKey.create({
    id: nextId,
    name,
    keyHash,
    keyPrefix,
    isActive: true,
    expiresAt: null,
    lastUsedAt: null,
  });

  console.log('\n=== API Key Generated ===');
  console.log(`Name: ${name}`);
  console.log(`API Key: ${apiKey}`);
  console.log(`Prefix: ${keyPrefix}`);
  console.log('\nIMPORTANT: Save this API key securely. It will not be shown again.');
  console.log('Use this key in the X-API-Key header for API requests.');

  await mongoose.disconnect();
  console.log('\nDisconnected from MongoDB');
}

// Get key name from command line argument
const keyName = process.argv[2] || 'Default Key';
generateApiKey(keyName).catch((error) => {
  console.error('Failed to generate API key:', error);
  process.exit(1);
});
