import { join, sep } from 'node:path';
import { runner } from 'node-pg-migrate';
import { loadEnvironment } from '../../../libs/configuration/src';

/**
 * Resolves the `backend/migrations` directory relative to this file's own
 * location rather than `process.cwd()`, so migrations run identically from
 * the compiled `dist/apps/api/src/migration.js` (production/deploy) and from
 * the TypeScript source at `apps/api/src/migration.ts` (ts-jest integration
 * tests), even though those two locations sit at different directory depths
 * relative to the `backend/` package root.
 */
function resolveMigrationsDir(): string {
  const segments = __dirname.split(sep);
  const distIndex = segments.lastIndexOf('dist');
  const backendRoot =
    distIndex !== -1
      ? segments.slice(0, distIndex).join(sep)
      : segments.slice(0, -3).join(sep);
  return join(backendRoot, 'migrations');
}

export async function runMigrations(): Promise<void> {
  const env = loadEnvironment(process.env);
  await runner({
    databaseUrl: env.databaseUrl,
    dir: resolveMigrationsDir(),
    direction: 'up',
    count: Infinity,
    migrationsTable: 'pgmigrations',
    checkOrder: true,
    log: (message: string) => console.log(message),
  });
}

if (require.main === module) {
  void runMigrations().catch((error) => {
    console.error(error);
    process.exitCode = 1;
  });
}
