/**
 * Seed script to create an API key in the database
 * Usage: tsx scripts/seed-api-key.ts [key] [label]
 */

import { getPrismaClient } from '../src/db/prisma.js';
import { getPersistenceMode } from '../src/config/persistence.js';
import * as crypto from 'crypto';

async function seedApiKey() {
  const mode = getPersistenceMode();
  
  if (mode === 'memory') {
    console.error('❌ Cannot seed API keys in memory mode.');
    console.error('   Use API_KEY environment variable instead.');
    process.exit(1);
  }

  // Generate a random API key if not provided
  const key = process.argv[2] || crypto.randomBytes(32).toString('hex');
  const label = process.argv[3] || 'Default API Key';

  try {
    const prisma = await getPrismaClient();
    
    // Check if key already exists
    const existing = await prisma.apiKey.findUnique({
      where: { key },
    });

    if (existing) {
      console.log(`⚠️  API key already exists: ${key}`);
      console.log(`   Label: ${existing.label || 'N/A'}`);
      console.log(`   Revoked: ${existing.revoked}`);
      process.exit(0);
    }

    // Create new API key
    const apiKey = await prisma.apiKey.create({
      data: {
        key,
        label,
        revoked: false,
      },
    });

    console.log('✅ API key created successfully!');
    console.log(`   ID: ${apiKey.id}`);
    console.log(`   Key: ${apiKey.key}`);
    console.log(`   Label: ${apiKey.label || 'N/A'}`);
    console.log(`   Created at: ${apiKey.createdAt.toISOString()}`);
    console.log('\n📝 Usage:');
    console.log(`   curl -H "x-api-key: ${apiKey.key}" http://localhost:3000/api/runs`);
    
    await prisma.$disconnect();
  } catch (error) {
    console.error('❌ Error seeding API key:', error);
    process.exit(1);
  }
}

seedApiKey();

