/**
 * fix-template-currenturl
 *
 * Rewrites the JSON-LD canonical url construction in
 * src/app/** /template.tsx from
 *
 *   const currentUrl = URL + pathname + searchParams;
 *
 * to
 *
 *   const currentUrl = `${URL}${pathname}`;
 *
 * Why: in the Next 16 / React 19 model `searchParams` is a
 * ReadonlyURLSearchParams that string-coerces differently on the server
 * and the client. The mismatched output lands inside a JSON-LD
 * <script dangerouslySetInnerHTML> tag, breaks hydration of the entire
 * route subtree, and races sibling client component hydration — auth
 * forms in particular have shipped credentials into the URL as native
 * GETs because their onSubmit listener was not yet attached when the
 * user clicked submit.
 *
 * Handles both base forms observed across brands:
 *   const currentUrl = URL + pathname + searchParams;
 *   const currentUrl = process.env.NEXT_PUBLIC_URL + pathname + searchParams;
 *
 * Files outside src/app/** /template.tsx are skipped. Files that already
 * use the template-literal form are no-ops.
 *
 * Usage:
 *   node codemods/fix-template-currenturl/index.js [--dry-run]
 *   npx @akinon/projectzero codemod --codemod=fix-template-currenturl [--dry-run]
 */

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}] ${msg}`);
}

const transform = () => {
  const cwd = path.resolve(process.cwd());
  const dryRun = process.argv.includes('--dry-run');
  const transformPath = path.join(__dirname, 'transform.js');
  const srcPath = path.join(cwd, 'src', 'app');

  if (!fs.existsSync(srcPath)) {
    log(`fix-template-currenturl: no src/app at ${cwd}, skipping`);
    return Promise.resolve();
  }

  log(
    `fix-template-currenturl: scanning ${srcPath}${dryRun ? ' (dry-run)' : ''}`
  );

  return jscodeshift
    .run(transformPath, [srcPath], {
      verbose: 0,
      dry: dryRun,
      print: dryRun,
      extensions: 'tsx',
      parser: 'tsx',
      ignorePattern: '**/node_modules/**',
      silent: true
    })
    .then((res) => {
      log(
        `fix-template-currenturl: ${res.ok} ok, ${res.nochange} unchanged, ${res.skip} skipped, ${res.error} errors`
      );
    });
};

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);
    });
  }
}
