/**
 * migrate-page-types: rewrites `PageProps<T>` from `@akinon/next/types` into
 * `AsyncPageProps<T>` / `ResolvedPageProps<T>` across a brand's `src/`.
 *
 * Why: `@next/codemod next-async-request-api` updates the call sites
 * (`await props.params`, `use(props.params)`), but the @akinon/next legacy
 * `PageProps<T>` type is still sync and clashes with Next 16's internal
 * `.next/types/.../page.ts` validator. Manually fixing every brand on every
 * upgrade is the same change repeated — this codemod automates it.
 *
 * Usage:
 *   cd <brand-root>
 *   npx @akinon/projectzero codemod --codemod=migrate-page-types [--dry-run]
 *
 * Or via the upgrade-to-2 chain (no flag needed).
 */

const path = require('path');
const fs = require('fs');
const jscodeshift = require('jscodeshift/src/Runner');

function log(msg) {
  const ts = new Date().toISOString().replace('T', ' ').slice(0, 19);
  console.log(`[${ts}] [migrate-page-types] ${msg}`);
}

const transform = () => {
  const workingDir = path.resolve(process.cwd());
  const dryRun = process.argv.includes('--dry-run');

  log(`starting in ${workingDir}${dryRun ? ' (DRY RUN)' : ''}`);

  const srcDir = path.join(workingDir, 'src');
  if (!fs.existsSync(srcDir)) {
    log('No src/ directory found, nothing to migrate.');
    return Promise.resolve();
  }

  const transformPath = path.resolve(__dirname, 'transform.js');

  return jscodeshift
    .run(transformPath, [srcDir], {
      verbose: 0,
      dry: Boolean(dryRun),
      print: Boolean(dryRun),
      extensions: 'ts,tsx',
      parser: 'tsx',
      ignorePattern: '**/node_modules/**',
      silent: true
    })
    .then(
      (stats) => {
        log(
          `${stats.ok} changed, ${stats.nochange} unchanged, ${stats.error} errored`
        );
        log('done');
      },
      (err) => {
        log(`FAILED: ${err.message}`);
        throw err;
      }
    );
};

module.exports = { transform };

if (require.main === module) {
  const result = transform();
  if (result && typeof result.then === 'function') {
    result.catch((err) => {
      console.error(err);
      process.exit(1);
    });
  }
}
