import postgres from 'postgres';
import { readFileSync } from 'fs';
import { join } from 'path';
import 'dotenv/config';

const connectionString = `postgres://${process.env.POSTGRES_USER || 'postgres'}:${process.env.POSTGRES_PASSWORD || ''}@${process.env.POSTGRES_HOST || 'localhost'}:${process.env.POSTGRES_PORT || '5432'}/${process.env.POSTGRES_DB || 'scriba'}`;

console.log('Connection string:', connectionString.replace(/:[^:@]*@/, ':****@'));

const sql = postgres(connectionString);

async function runMigration() {
  try {
    const migrationPath = join(process.cwd(), 'drizzle', '0000_cuddly_christian_walker.sql');
    const migrationSQL = readFileSync(migrationPath, 'utf-8');
    
    console.log('Running migration...');
    await sql.unsafe(migrationSQL);
    console.log('Migration completed successfully!');
  } catch (error) {
    console.error('Migration failed:', error);
    throw error;
  } finally {
    await sql.end();
  }
}

runMigration();
