import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
import * as dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

dotenv.config({ path: ['.env.local', '.env'] });

const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
  console.error('DATABASE_URL is not set');
  process.exit(1);
}

// Using max: 1 connection since it's only for migration
const migrationClient = postgres(connectionString, { max: 1 });
const db = drizzle(migrationClient);

const runMigrations = async () => {
  console.log('Running database migrations...');
  try {
    const folder = path.join(__dirname, '../drizzle');
    // print all migrations
    const migrations = await fs.readdir(folder);
    console.log('Migrations:', JSON.stringify(migrations));

    await migrate(db, { migrationsFolder: folder });
    console.log('Migrations completed successfully.');
  } catch (err) {
    console.error('Error running migrations:', err);
    process.exit(1);
  } finally {
    await migrationClient.end();
  }
};

runMigrations();
