import { execSync } from 'node:child_process';
import * as fs from 'node:fs';
import { join } from 'node:path';
import { getBaseTemplatesDir } from '../engine/template-engine.js';
import { copyDirRecursive } from './handler-utils.js';
export async function newMonorepo(appName, _flags) {
    if (!appName)
        throw new Error('Project name is required to create a monorepo');
    const templatesDir = getBaseTemplatesDir();
    // 1. Copy monorepo scaffold
    const monorepoSrc = join(templatesDir, 'monorepo');
    if (!fs.existsSync(monorepoSrc)) {
        throw new Error(`Monorepo template not found at ${monorepoSrc}`);
    }
    copyDirRecursive(monorepoSrc, appName);
    // 2. Copy backend application template
    const backAppSrc = join(templatesDir, 'backend', 'application');
    if (!fs.existsSync(backAppSrc)) {
        throw new Error(`Backend application template not found at ${backAppSrc}`);
    }
    copyDirRecursive(backAppSrc, join(appName, 'backend'));
    // 3. Copy frontend application template
    const frontAppSrc = join(templatesDir, 'frontend', 'application');
    if (!fs.existsSync(frontAppSrc)) {
        throw new Error(`Frontend application template not found at ${frontAppSrc}`);
    }
    copyDirRecursive(frontAppSrc, join(appName, 'frontend'));
    // 4. Run pnpm install (clean env to avoid inheriting ts-node loader from dev mode)
    const cleanEnv = { ...process.env };
    delete cleanEnv.NODE_OPTIONS;
    execSync('pnpm install', { cwd: appName, env: cleanEnv, stdio: 'inherit' });
    // 5. Copy backend .env file
    const envSrc = join(templatesDir, 'backend', 'env', '.env');
    if (fs.existsSync(envSrc)) {
        fs.copyFileSync(envSrc, join(appName, 'backend', '.env'));
    }
    // 6. Generate GraphQL types
    execSync('pnpm --filter aurora-back graphql:types', {
        cwd: appName,
        env: cleanEnv,
        stdio: 'inherit',
    });
}
