#!/usr/bin/env node
/**
 * Fix CSRF Header Names Script
 *
 * Replaces all instances of 'X-CSRF-Token' with 'x-csrf-token'
 * to match the expected header name in lib/csrf.ts
 */

const fs = require('fs');
const path = require('path');

const filesToFix = [
  'app/[lang]/signup/company-info/page.tsx',
  'app/[lang]/signup/verify/page.tsx',
  'app/[lang]/signup/page.tsx',
  'app/[lang]/dashboard/components/BillingPanel.tsx',
  'app/[lang]/dashboard/DashboardClient.tsx',
];

let totalReplacements = 0;

console.log('🔧 Fixing CSRF header names...\n');

filesToFix.forEach((file) => {
  const filePath = path.join(process.cwd(), file);

  if (!fs.existsSync(filePath)) {
    console.log(`⚠️  Skipping ${file} (not found)`);
    return;
  }

  let content = fs.readFileSync(filePath, 'utf-8');
  const before = content;

  // Replace both single and double quote versions
  content = content.replace(/"X-CSRF-Token"/g, '"x-csrf-token"');
  content = content.replace(/'X-CSRF-Token'/g, "'x-csrf-token'");

  if (content !== before) {
    fs.writeFileSync(filePath, content, 'utf-8');
    const count = (before.match(/X-CSRF-Token/g) || []).length;
    totalReplacements += count;
    console.log(`✅ Fixed ${file} (${count} replacement${count > 1 ? 's' : ''})`);
  } else {
    console.log(`✓  ${file} (already correct)`);
  }
});

console.log(`\n✅ Total replacements: ${totalReplacements}`);
console.log('✅ All CSRF header names have been standardized to lowercase');
