import { formatFrontWorkspaceFiles, swapCurrentAccountAdapter, } from '../../front-package-helpers.js';
/**
 * Log a warning and continue when a CodeWriter method fails, matching the
 * behavior of the `generate front` path (design D4 / safeRun contract).
 */
function safeRun(label, fn) {
    try {
        fn();
    }
    catch (error) {
        console.warn(`[aurora-catalyst:front-installer] ${label} skipped: ${error.message}`);
    }
}
/**
 * Identity (IAM + OAuth) FRONTEND package installer.
 *
 * Runs after both the `iam` and `o-auth` template trees have been copied by
 * the meta-package dispatch in `addFrontPackage`. Responsible for wiring the
 * four shared composition-root files via the three idempotent CodeWriter
 * methods and the new `swapCurrentAccountAdapter` op.
 *
 * Execution order (design D4):
 * 1. For each member BC (`iam`, `o-auth`):
 *    a. `declareFrontBoundedContext()` — wire lazy route in `routes.ts`.
 *    b. `registerFrontNavigation()` — add nav import + spread in `navigation-data.ts`.
 *    c. `registerBcAggregatorInNavMain(srcDirectory, bc)` — add icons spread in `nav-main.ts`.
 * 2. Once (iam-specific): `swapCurrentAccountAdapter(ctx)` — swap provider in `aurora.provider.ts`.
 * 3. Consumer-Prettier format pass on all four touched files (cosmetic, non-fatal).
 *
 * MUST NOT:
 * - Add npm dependencies.
 * - Touch `domains/auth/` or `public/i18n/navigation/`.
 *
 * Returns a concise post-install banner surfaced by the `add` command after
 * `spinner.succeed()`.
 */
export default async function install(ctx) {
    // 1. Wire routes / nav / icons for each member BC (both idempotent)
    for (const bc of ['iam', 'o-auth']) {
        const cw = ctx.codeWriterFor(bc);
        safeRun(`declareFrontBoundedContext(${bc})`, () => cw.declareFrontBoundedContext());
        safeRun(`registerFrontNavigation(${bc})`, () => cw.registerFrontNavigation());
        safeRun(`registerBcAggregatorInNavMain(${bc})`, () => cw.registerBcAggregatorInNavMain(ctx.srcDirectory, bc));
    }
    // 2. Swap the CurrentAccountService provider to use the IAM adapter (iam-specific, idempotent)
    safeRun('swapCurrentAccountAdapter', () => swapCurrentAccountAdapter(ctx));
    // 3. Consumer-Prettier format pass on the four touched shared files (non-fatal)
    await formatFrontWorkspaceFiles(ctx, [
        'src/app/domains/admin/routes.ts',
        'src/app/domains/admin/navigation-data.ts',
        'src/app/domains/admin/layout/sidebar/nav-main.ts',
        'src/app/aurora.provider.ts',
    ]);
    return 'Identity (IAM + OAuth) frontend installed — iam + o-auth routed, in the sidebar, and the IAM current-account adapter is active.';
}
