#!/usr/bin/env tsx
/**
 * Manual Phase 2 migration - Fixing multi-statement bug
 */

import { createClient } from '@libsql/client';
import { config } from 'dotenv';

config();

const TURSO_URL = process.env.TURSO_URL!;
const TURSO_AUTH_TOKEN = process.env.TURSO_AUTH_TOKEN!;

const db = createClient({
  url: TURSO_URL,
  authToken: TURSO_AUTH_TOKEN,
});

async function phase2Migration() {
  console.log('\n🔧 Phase 2 Migration - api_key → api_key_hash\n');

  try {
    // Step 1: Check if api_key_hash already exists
    console.log('Checking if api_key_hash column exists...');
    const colCheck = await db.execute(`SELECT COUNT(*) as count FROM pragma_table_info('users') WHERE name='api_key_hash'`);
    const hasApiKeyHash = (colCheck.rows[0] as any).count > 0;

    if (!hasApiKeyHash) {
      console.log('Adding api_key_hash column...');
      await db.execute('ALTER TABLE users ADD COLUMN api_key_hash TEXT');
      console.log('✅ Added api_key_hash column');
    } else {
      console.log('⏭️  api_key_hash column already exists');
    }

    // Step 2: Copy data from api_key to api_key_hash
    console.log('\nCopying data from api_key to api_key_hash...');
    const result = await db.execute(`
      UPDATE users
      SET api_key_hash = api_key
      WHERE api_key IS NOT NULL AND (api_key_hash IS NULL OR api_key_hash = '')
    `);
    console.log(`✅ Copied ${result.rowsAffected} rows`);

    // Step 3: Update index
    console.log('\nUpdating indexes...');

    // Drop old index
    try {
      await db.execute('DROP INDEX IF EXISTS idx_users_api_key');
      console.log('✅ Dropped idx_users_api_key');
    } catch (error: any) {
      console.log(`⏭️  idx_users_api_key already dropped`);
    }

    // Create new index
    await db.execute('CREATE INDEX IF NOT EXISTS idx_users_api_key_hash ON users(api_key_hash)');
    console.log('✅ Created idx_users_api_key_hash');

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

  } catch (error) {
    console.error('❌ Phase 2 migration failed:', error);
    process.exit(1);
  }
}

phase2Migration().catch(console.error);
