/**
 * fix-login-form-action
 *
 * Rewrites the login form's `action="/api/auth/signin/credentials"` attribute
 * in src/views/login/index.tsx to `action={() => {}}`.
 *
 * Why: under React 19 the form `action` prop is a function-action signal —
 * passing one tells React itself to call event.preventDefault() before any
 * listener runs. With the string URL it used to have, a hydration race
 * (e.g. searchParams CSR bailout) would let the browser perform a native
 * submit to the auth endpoint before the JS onSubmit listener attached.
 * On the credentials login form that meant POSTing email and password as
 * form-encoded body. The no-op function neutralizes that fallback while
 * keeping the existing JS onSubmit as the real submit path.
 *
 * Brands without the attribute (or without src/views/login/index.tsx) are
 * clean no-ops.
 *
 * Usage:
 *   node codemods/fix-login-form-action/index.js [--dry-run]
 *   npx @akinon/projectzero codemod --codemod=fix-login-form-action [--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 target = path.join(cwd, 'src', 'views', 'login', 'index.tsx');

  if (!fs.existsSync(target)) {
    log(
      `fix-login-form-action: no src/views/login/index.tsx at ${cwd}, skipping`
    );
    return Promise.resolve();
  }

  log(
    `fix-login-form-action: scanning ${target}${dryRun ? ' (dry-run)' : ''}`
  );

  return jscodeshift
    .run(transformPath, [target], {
      verbose: 0,
      dry: dryRun,
      print: dryRun,
      extensions: 'tsx',
      parser: 'tsx',
      ignorePattern: '**/node_modules/**',
      silent: true
    })
    .then((res) => {
      log(
        `fix-login-form-action: ${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);
    });
  }
}
