import { drizzle } from 'drizzle-orm/libsql';
import { migrate } from 'drizzle-orm/libsql/migrator';
import { createClient } from '@libsql/client';
import { env } from '../env';

export async function runMigrations(): Promise<void> {
  const client = createClient({ url: env.DATABASE_URL });
  const db = drizzle(client);
  await migrate(db, { migrationsFolder: './drizzle' });
  client.close();
}

// Allow running directly: `tsx src/db/migrate.ts`
if (import.meta.url === `file://${process.argv[1]}`) {
  runMigrations()
    .then(() => {
      console.log('Migrations applied.');
      process.exit(0);
    })
    .catch((err) => {
      console.error(err);
      process.exit(1);
    });
}
