#!/usr/bin/env node

/**
 * Script to fix TypeScript imports from relative paths to path aliases
 *
 * Replaces:
 * - from '../../domain/...' → from '@domain/...'
 * - from '../../../domain/...' → from '@domain/...'
 * - from '../domain/...' → from '@domain/...'
 * - from '../../../../domain/...' → from '@domain/...'
 */

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

function fixImportsInFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  let modified = content;

  // Replace all variations of relative domain imports with @domain alias
  modified = modified.replace(/from ['"]\.\.\/\.\.\/\.\.\/\.\.\/domain\//g, "from '@domain/");
  modified = modified.replace(/from ['"]\.\.\/\.\.\/\.\.\/domain\//g, "from '@domain/");
  modified = modified.replace(/from ['"]\.\.\/\.\.\/domain\//g, "from '@domain/");
  modified = modified.replace(/from ['"]\.\.\/domain\//g, "from '@domain/");

  // Also fix import statements (not just from)
  modified = modified.replace(
    /import\s+(['"])\.\.\/\.\.\/\.\.\/\.\.\/domain\//g,
    'import $1@domain/'
  );
  modified = modified.replace(/import\s+(['"])\.\.\/\.\.\/\.\.\/domain\//g, 'import $1@domain/');
  modified = modified.replace(/import\s+(['"])\.\.\/\.\.\/domain\//g, 'import $1@domain/');
  modified = modified.replace(/import\s+(['"])\.\.\/domain\//g, 'import $1@domain/');

  if (modified !== content) {
    fs.writeFileSync(filePath, modified, 'utf8');
    return true;
  }
  return false;
}

function walkDir(dir) {
  const files = fs.readdirSync(dir);
  let count = 0;

  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      count += walkDir(filePath);
    } else if (file.endsWith('.ts')) {
      if (fixImportsInFile(filePath)) {
        console.log(`✅ Fixed: ${filePath}`);
        count++;
      }
    }
  }

  return count;
}

const srcDir = path.join(__dirname, 'src');
console.log('🔧 Fixing TypeScript imports...\n');

const count = walkDir(srcDir);

console.log(`\n✅ Fixed ${count} files`);
