/**
 * Fix Missing IDs in audit_logs.create() Calls
 *
 * This script automatically adds missing ID fields to all audit_logs.create() calls
 * and ensures createId is imported.
 */

import * as fs from 'fs';
import * as path from 'path';

const FILES_TO_FIX = [
  'app/api/auth/verify-signup-otp/route.ts',
  'app/api/auth/verify-login-otp/route.ts',
  'app/api/auth/verify-otp-and-activate/route.ts',
  'app/api/auth/session-from-otp/route.ts',
  'app/api/auth/reset-password/route.ts',
  'app/api/auth/forgot-password/route.ts',
  'app/api/auth/verify-email-only/route.ts',
  'app/api/billing/change-plan/route.ts',
  'app/api/signup/company-info/route.ts',
  'app/api/onboarding/company-info/route.ts',
];

function fixFile(filePath: string): { success: boolean; changes: number } {
  const fullPath = path.join(process.cwd(), filePath);

  if (!fs.existsSync(fullPath)) {
    console.log(`❌ File not found: ${filePath}`);
    return { success: false, changes: 0 };
  }

  let content = fs.readFileSync(fullPath, 'utf-8');
  let changes = 0;

  // Check if file has audit_logs.create
  if (!content.includes('prisma.audit_logs.create')) {
    console.log(`  ℹ️  No audit logs in ${filePath}`);
    return { success: true, changes: 0 };
  }

  // Add createId import if missing
  if (!content.includes('createId')) {
    // Find the last import statement
    const importRegex = /import .+ from ['"@].+['"];?\n/g;
    const imports = content.match(importRegex);

    if (imports && imports.length > 0) {
      const lastImport = imports[imports.length - 1];
      const importInsertPoint = content.lastIndexOf(lastImport) + lastImport.length;

      content =
        content.slice(0, importInsertPoint) +
        "import { createId } from '@paralleldrive/cuid2';\n" +
        content.slice(importInsertPoint);

      changes++;
      console.log(`  ✅ Added createId import`);
    }
  }

  // Fix audit_logs.create() calls missing id field
  // Pattern: data: { (whitespace) userId or type (without id field before it)
  const auditCreateRegex = /(await prisma\.audit_logs\.create\(\{\s*data: \{)(\s*(?!id:))/g;

  const matches = content.match(auditCreateRegex);
  if (matches) {
    content = content.replace(
      auditCreateRegex,
      '$1\n          id: createId(),$2'
    );

    changes += matches.length;
    console.log(`  ✅ Fixed ${matches.length} audit_logs.create() call(s)`);
  }

  // Write back to file
  fs.writeFileSync(fullPath, content, 'utf-8');

  return { success: true, changes };
}

console.log('🔧 Fixing Missing IDs in audit_logs.create() Calls\n');

let totalChanges = 0;
let filesFixed = 0;

for (const file of FILES_TO_FIX) {
  console.log(`\n📄 Processing: ${file}`);
  const result = fixFile(file);

  if (result.success && result.changes > 0) {
    filesFixed++;
    totalChanges += result.changes;
  }
}

console.log(`\n\n📊 Summary:`);
console.log(`   Files processed: ${FILES_TO_FIX.length}`);
console.log(`   Files fixed: ${filesFixed}`);
console.log(`   Total changes: ${totalChanges}`);

if (totalChanges > 0) {
  console.log(`\n✅ All fixes applied successfully!`);
  console.log(`   Run 'npm run dev' to reload the server with changes.`);
} else {
  console.log(`\n✨ No fixes needed - all files already have IDs!`);
}
