import { generateKeyPairSync } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
export function resolvePlanFiles(plan) {
    const warnings = [];
    let keysGenerated = false;
    // ─── Nginx directives (all targets) ──────────────────────────────
    if (!plan.skipHosting) {
        const nginxPath = join(plan.dir, 'nginx.conf');
        if (existsSync(nginxPath)) {
            plan.nginxDirectives = readFileSync(nginxPath, 'utf8');
        }
    }
    if (plan.skipCicd) {
        return { keysGenerated, warnings };
    }
    if (plan.target === 'back') {
        const privPath = join(plan.dir, 'oauth-private.key');
        const pubPath = join(plan.dir, 'oauth-public.key');
        if (!existsSync(privPath) || !existsSync(pubPath)) {
            const { privateKey, publicKey } = generateKeyPairSync('rsa', {
                modulusLength: 2048,
                privateKeyEncoding: { format: 'pem', type: 'pkcs1' },
                publicKeyEncoding: { format: 'pem', type: 'pkcs1' },
            });
            mkdirSync(plan.dir, { recursive: true });
            writeFileSync(privPath, privateKey);
            writeFileSync(pubPath, publicKey);
            keysGenerated = true;
        }
        plan.oauthPrivateKey = readFileSync(privPath, 'utf8');
        plan.oauthPublicKey = readFileSync(pubPath, 'utf8');
        if (plan.dotEnvEnc) {
            const dotEnvPath = join(plan.dir, plan.dotEnvEnc);
            if (existsSync(dotEnvPath)) {
                plan.dotEnv = readFileSync(dotEnvPath, 'utf8');
            }
            else {
                warnings.push(`Encrypted .env not found: ${dotEnvPath}`);
            }
        }
        plan.sopsAgeKey = process.env.SOPS_AGE_SECRET_KEY;
        if (!plan.sopsAgeKey) {
            warnings.push('SOPS_AGE_SECRET_KEY environment variable not set');
        }
    }
    return { keysGenerated, warnings };
}
