#!/usr/bin/env node
/**
 * Verify Circular Dependencies
 *
 * Safely checks for circular dependency issues by importing the AppModule
 * without bootstrapping the application (no server start, no DB connections).
 *
 * Usage: node scripts/verify-circular-deps.mjs
 */

import { existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const projectRoot = join(__dirname, '..');
const distPath = join(projectRoot, 'dist');

console.log('🔍 Checking for circular dependencies...\n');

// Check if dist exists
if (!existsSync(distPath)) {
  console.error('❌ dist/ directory not found. Run pnpm build first.\n');
  process.exit(1);
}

// Check if app.module.js exists
const appModulePath = join(distPath, 'app.module.js');
if (!existsSync(appModulePath)) {
  console.error('❌ dist/app.module.js not found. Run pnpm build first.\n');
  process.exit(1);
}

// Set environment to avoid side effects
process.env.NODE_ENV = 'test';
process.env.SKIP_BOOTSTRAP = 'true';

try {
  // Dynamically import the AppModule to check for circular dependencies
  await import(appModulePath);

  console.log('✅ No circular dependency issues detected');
  console.log('   All modules and entities loaded successfully\n');
  process.exit(0);
} catch (error) {
  console.error('❌ Circular dependency detected!\n');
  console.error('Error:', error.message);
  console.error('\nStack trace:');
  console.error(error.stack);
  console.error('\n💡 Hint: Look for entities with bidirectional relations.');
  console.error("   Use string references in decorators: @ManyToOne('EntityName', ...)\n");
  process.exit(1);
}
