import { saveOwnerConfig, deleteOnboardingSession, } from "../config/index.js";
import { logger } from "../logger.js";
import { sendWelcomeMessages } from "./send-invite.js";
/**
 * Telegram onboarding handler.
 *
 * Validates the /start verification code and finalizes onboarding.
 * Language and timezone preferences are collected after onboarding
 * completes, via the normal /settings flow.
 */
export class TelegramOnboardingHandler {
    ownerConfig;
    config;
    channelManager;
    _isComplete = false;
    constructor(ownerConfig, config, _botToken, channelManager) {
        this.ownerConfig = ownerConfig;
        this.config = config;
        this.channelManager = channelManager;
    }
    get isComplete() {
        return this._isComplete;
    }
    /**
     * Replace the cached owner config (called when the server reports
     * a changed email so the handler validates against the new code).
     */
    updateOwnerConfig(updated) {
        this.ownerConfig = updated;
    }
    /**
     * Process a Telegram message during onboarding.
     * Returns true when onboarding is complete.
     */
    async handleMessage(msg, sendReply) {
        if (this._isComplete)
            return true;
        const chatId = typeof msg.meta?.chatId === "number" ? msg.meta.chatId : null;
        if (chatId === null) {
            logger.warn("Onboarding: received message without chatId metadata");
            return false;
        }
        const text = msg.text.trim();
        if (!this.ownerConfig.onboardingCodeVerified) {
            return this.handleCodeVerification(text, chatId, sendReply);
        }
        // Code already verified (e.g. resumed after crash) — finalize directly
        await this.finalizeOnboarding(chatId, sendReply);
        return true;
    }
    /**
     * Validate the /start verification code and finalize onboarding.
     */
    async handleCodeVerification(text, chatId, sendReply) {
        const match = /^\/start\s+(\S+)$/i.exec(text);
        const code = match?.[1];
        if (!code) {
            await sendReply(chatId, "Welcome! To get started, please send your verification code:\n\n" +
                "/start YOUR_CODE\n\nYou can find the code in the setup email.");
            return false;
        }
        if (code !== this.ownerConfig.onboardingCode) {
            await sendReply(chatId, "That verification code doesn't match. Please check the email and try again.\n\n" +
                "/start YOUR_CODE");
            return false;
        }
        this.ownerConfig.onboardingCodeVerified = true;
        this.ownerConfig.telegramChatId = chatId;
        saveOwnerConfig(this.ownerConfig);
        logger.system(`Onboarding: code verified for chat ${chatId}`);
        await this.finalizeOnboarding(chatId, sendReply);
        return true;
    }
    async finalizeOnboarding(chatId, sendReply) {
        this.ownerConfig.onboardingComplete = true;
        this.ownerConfig.onboardedAt = new Date().toISOString();
        this.ownerConfig.onboardingCode = undefined;
        saveOwnerConfig(this.ownerConfig);
        this.channelManager.clearTelegramPreOwnerAccessState();
        deleteOnboardingSession();
        const name = this.ownerConfig.ownerName || "there";
        await sendReply(chatId, `Hi ${name}! Your verification is complete and I'm all set up. Looking forward to working with you!`);
        await sendWelcomeMessages(this.config, this.ownerConfig, this.channelManager);
        // TODO: Disabled for now
        // try {
        //   await sendIdentityCredentials(this.config, this.ownerConfig, this.channelManager);
        // } catch (err) {
        //   logger.warn(
        //     `Failed to send identity credentials: ${err instanceof Error ? err.message : String(err)}`,
        //   );
        // }
        this._isComplete = true;
        logger.system(`Onboarding complete! Agent "${this.config.agentName}" for owner "${this.ownerConfig.ownerName}"`);
    }
}
//# sourceMappingURL=telegram-onboarding.js.map