import { z } from 'zod';
import { authMiddleware } from '../../auth/middleware.js';
import { supabase } from '../../utils/supabase.js';
import { startTelegramSession, disconnectTelegramSession, getTelegramStatus, } from './adapter.js';
import { upsertFact } from '../../autonomy/identity.js';
const connectSchema = z.object({
    token: z.string().min(20).max(200),
});
async function resolveTenantId(userId) {
    if (!userId)
        return null;
    const { data } = await supabase
        .from('tenants')
        .select('id')
        .eq('owner_id', userId)
        .order('created_at', { ascending: false })
        .limit(1);
    const row = data?.[0];
    return row?.id ?? null;
}
export async function registerTelegramRoutes(app) {
    app.get('/api/channels/telegram/status', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req.user?.id);
        if (!tenantId)
            return reply.status(401).send({ error: 'No tenant' });
        reply.send({ data: getTelegramStatus(tenantId) });
    });
    app.post('/api/channels/telegram/connect', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req.user?.id);
        if (!tenantId)
            return reply.status(401).send({ error: 'No tenant' });
        const parsed = connectSchema.safeParse(req.body);
        if (!parsed.success)
            return reply.status(400).send({ error: parsed.error.flatten() });
        const session = await startTelegramSession(tenantId, parsed.data.token);
        if (session.status === 'auth_failed') {
            return reply.status(400).send({ error: 'Invalid bot token — get a new one from @BotFather' });
        }
        // Persist the token so boot.js auto-starts Telegram on every restart
        // (mirrors the chat-paste path; without this a dashboard connect was
        // lost on the next gateway restart).
        try {
            await upsertFact(tenantId, 'channel.telegram_bot_token', parsed.data.token, 'channel', 'owner');
        }
        catch { /* non-fatal — session already running this process */ }
        reply.send({ data: getTelegramStatus(tenantId) });
    });
    app.post('/api/channels/telegram/disconnect', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req.user?.id);
        if (!tenantId)
            return reply.status(401).send({ error: 'No tenant' });
        await disconnectTelegramSession(tenantId);
        // Clear the persisted token so boot.js does not auto-restart a session
        // the owner explicitly disconnected. (Empty value is falsy in boot.js.)
        try {
            await upsertFact(tenantId, 'channel.telegram_bot_token', '', 'channel', 'owner');
        }
        catch { /* non-fatal */ }
        reply.send({ data: { status: 'disconnected' } });
    });
}
//# sourceMappingURL=routes.js.map