#!/usr/bin/env tsx
import { createClient } from '@libsql/client';
import { config } from 'dotenv';

config();

const db = createClient({
  url: process.env.TURSO_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN!,
});

async function completePhase2() {
  console.log('\n🔧 Completing Phase 2 - Update api_key index\n');

  try {
    // Check what index exists
    console.log('Checking existing indexes...');
    const oldIdx = await db.execute(`SELECT COUNT(*) as count FROM sqlite_master WHERE type='index' AND name='idx_users_api_key'`);
    const newIdx = await db.execute(`SELECT COUNT(*) as count FROM sqlite_master WHERE type='index' AND name='idx_users_api_key_hash'`);

    console.log(`  idx_users_api_key: ${(oldIdx.rows[0] as any).count > 0 ? 'EXISTS' : 'NOT FOUND'}`);
    console.log(`  idx_users_api_key_hash: ${(newIdx.rows[0] as any).count > 0 ? 'EXISTS' : 'NOT FOUND'}`);

    // Drop old index
    if ((oldIdx.rows[0] as any).count > 0) {
      await db.execute('DROP INDEX idx_users_api_key');
      console.log('✅ Dropped idx_users_api_key');
    }

    // Create new index
    if ((newIdx.rows[0] as any).count === 0) {
      await db.execute('CREATE INDEX idx_users_api_key_hash ON users(api_key_hash)');
      console.log('✅ Created idx_users_api_key_hash');
    } else {
      console.log('⏭️  idx_users_api_key_hash already exists');
    }

    console.log('\n🎉 Phase 2 complete!\n');

  } catch (error) {
    console.error('❌ Failed:', error);
    process.exit(1);
  }
}

completePhase2().catch(console.error);
