/**
 * Process-wide singleton accessor for `ChatV2Service`.
 *
 * The server wiring layer calls `getChatV2Service()` once and holds the
 * reference; tests can `resetChatV2Service()` to start fresh.
 *
 * @module services/chat-v2/chat-v2.singleton
 */
import { ChatV2Service } from './chat-v2.service.js';
import { loadChatV2Config } from './config.js';
let _instance = null;
/**
 * Return the process-wide `ChatV2Service`, constructing it on first call.
 *
 * @param overrides - Optional overrides passed when first constructed.
 *   Ignored on subsequent calls.
 * @returns The shared service instance
 */
export function getChatV2Service(overrides) {
    if (!_instance) {
        const config = overrides?.config ?? loadChatV2Config();
        _instance = new ChatV2Service({
            config,
            db: overrides?.db,
            getPresence: overrides?.getPresence,
            // F2b (#333) — forward the validator so the production composition
            // root in backend/src/index.ts can wire a teamId-existence /
            // tenant-membership check on the singleton on first construction.
            // Subsequent calls ignore overrides (existing contract).
            validateTeamMembership: overrides?.validateTeamMembership,
            now: overrides?.now,
        });
    }
    return _instance;
}
/**
 * Replace the process-wide instance. Intended for tests and graceful
 * shutdown paths; do not call from request handlers.
 *
 * @param next - Optional replacement; when omitted, the singleton is cleared
 */
export function setChatV2ServiceForTesting(next) {
    if (_instance && _instance !== next) {
        try {
            _instance.close();
        }
        catch {
            // ignore — already closed
        }
    }
    _instance = next;
}
/** Close the current instance (if any) and clear the singleton. */
export function resetChatV2Service() {
    setChatV2ServiceForTesting(null);
}
//# sourceMappingURL=chat-v2.singleton.js.map