import {} from "./schema.js";
import { VetraCloudEnvironmentProcessor } from "./index.js";
import { up } from "./migrations.js";
import { childLogger } from "document-model";
import { up as upSecrets } from "../../subgraphs/vetra-cloud-secrets/db/migrations.js";
import { OpenBaoTransitClient } from "../../subgraphs/vetra-cloud-secrets/openbao-transit.js";
import { createSecretsService, } from "../../subgraphs/vetra-cloud-secrets/services/secrets-service.js";
const logger = childLogger(["vetra-cloud-environment-factory"]);
const DEFAULT_TRANSIT_ROLE = "vetra-secrets";
/**
 * Wire a SecretsService for the processor. Returns null when OPENBAO_ADDR
 * is unset (test mode, local dev without OpenBao) — the processor will
 * keep emitting env vars inline in values.yaml in that case, same as
 * before the refactor. In production OPENBAO_ADDR is required.
 */
async function createSecretsServiceForProcessor(module) {
    const openbaoAddr = process.env.OPENBAO_ADDR;
    if (!openbaoAddr) {
        logger.warn("[secrets] OPENBAO_ADDR is not set — env entries will be emitted inline " +
            "in values.yaml. Set OPENBAO_ADDR to route secrets through the " +
            "encrypted vetra-secrets-controller path.");
        return null;
    }
    const secretsDb = (await module.relationalDb.createNamespace("vetra-cloud-secrets"));
    // Defensive: ensure tables exist. Idempotent — the subgraph runs the
    // same migrations on its own startup; whichever loads first wins.
    await upSecrets(secretsDb);
    const transit = new OpenBaoTransitClient({
        addr: openbaoAddr,
        role: process.env.OPENBAO_TRANSIT_ROLE ?? DEFAULT_TRANSIT_ROLE,
        keyNamePrefix: process.env.OPENBAO_TRANSIT_KEY_PREFIX,
    });
    return createSecretsService({ db: secretsDb, transit });
}
export const vetraCloudEnvironmentProcessorFactory = (module) => async (driveHeader) => {
    logger.info(`Creating processor for drive ${driveHeader.id}`);
    const db = await module.relationalDb.createNamespace("vetra-cloud-environments");
    await up(db);
    const documentView = module.getReadModel("document-view");
    const secretsService = await createSecretsServiceForProcessor(module);
    const processor = new VetraCloudEnvironmentProcessor(db, module.dispatch, documentView, secretsService);
    return [
        {
            processor,
            filter: {
                branch: ["main"],
                documentId: ["*"],
                documentType: ["powerhouse/vetra-cloud-environment", "powerhouse/document-drive"],
                scope: ["global"],
            },
        },
    ];
};
