import db from '@/db/models';
import { migrator, seeder } from '@/db/umzug';

async function reset(): Promise<void> {
  console.log('Resetting database (drop all tables, migrate, seed)...');
  // Drop every table in the public schema (including the umzug tracking tables)
  // so migrations and seeders re-apply from scratch. Avoids `DROP SCHEMA`, which
  // requires schema ownership the app DB user may not have.
  await db.sequelize.query(`
    DO $$
    DECLARE r RECORD;
    BEGIN
      FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP
        EXECUTE 'DROP TABLE IF EXISTS "' || r.tablename || '" CASCADE';
      END LOOP;
    END $$;
  `);
  await migrator.up();
  await seeder.up();
  await db.sequelize.close();
  console.log('Done.');
}

reset().catch((error) => {
  console.error(error);
  process.exit(1);
});
