/* eslint-disable no-console */
/**
 * Create Test API Key Script
 *
 * Creates a test user with active subscription and API key for plugin testing
 */

import { PrismaClient } from '@prisma/client';
import crypto from 'crypto';
import { hashPassword } from '../src/utils/encryption';

const prisma = new PrismaClient();

function hashApiKey(key: string): string {
  return crypto.createHash('sha256').update(key).digest('hex');
}

function generateApiKey(): string {
  // Generate a test API key with sk_test_ prefix
  const prefix = 'sk_test_';
  const randomPart = crypto.randomBytes(24).toString('base64url');
  return prefix + randomPart;
}

async function main() {
  console.log('🔧 Creating test user with API key...');

  const testEmail = 'test@press.zone';
  const testPassword = await hashPassword('test123456');

  try {
    // 1. Create or update test user
    const user = await prisma.user.upsert({
      where: { email: testEmail },
      update: {},
      create: {
        email: testEmail,
        password_hash: testPassword,
        status: 'active',
        email_verified: true,
      },
    });
    console.log('✅ Test user created:', user.email, 'ID:', user.id);

    // 2. Create or update active subscription
    const subscription = await prisma.subscription.upsert({
      where: { user_id: user.id },
      update: {
        status: 'active',
        plan_tier: 'professional',
        billing_cycle: 'monthly',
        current_period_start: new Date(),
        current_period_end: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
      },
      create: {
        user_id: user.id,
        plan_tier: 'professional',
        billing_cycle: 'monthly',
        status: 'active',
        current_period_start: new Date(),
        current_period_end: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
      },
    });
    console.log('✅ Subscription created:', subscription.plan_tier, 'Status:', subscription.status);

    // 3. Add initial credits
    const existingCreditTx = await prisma.creditTransaction.findFirst({
      where: { user_id: user.id },
      orderBy: { created_at: 'desc' },
    });

    if (!existingCreditTx) {
      // Create initial credit allocation
      await prisma.creditTransaction.create({
        data: {
          user_id: user.id,
          type: 'allocation',
          amount: 500000, // 500K credits for professional plan
          balance_after: 500000,
          description: 'Initial test credit allocation',
        },
      });
      console.log('✅ Initial credits allocated: 500,000');
    }

    // 4. Create API key
    const apiKeyValue = generateApiKey();
    const keyHash = hashApiKey(apiKeyValue);
    const prefix = apiKeyValue.substring(0, 12); // First 12 chars as prefix

    const _apiKey = await prisma.apiKey.create({
      data: {
        user_id: user.id,
        key_hash: keyHash,
        prefix: prefix,
        name: 'Test API Key for Plugin Testing',
        is_active: true,
      },
    });

    console.log('\n🎉 SUCCESS! Test API Key Created:');
    console.log('=====================================');
    console.log('API Key:', apiKeyValue);
    console.log('User Email:', testEmail);
    console.log('User ID:', user.id);
    console.log('Plan:', subscription.plan_tier);
    console.log('Credits: 500,000');
    console.log('=====================================');
    console.log('\nUse this key in your plugin settings or TPZ_API_KEY env var.');

  } catch (error) {
    console.error('❌ Error creating test user:', error);
    process.exit(1);
  }
}

main()
  .catch((e) => {
    console.error('❌ Script failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
