import { authMiddleware } from '../../auth/middleware.js';
import { supabase } from '../../utils/supabase.js';
import { startDiscordSession, disconnectDiscordSession, getDiscordStatus } from './adapter.js';
import { z } from 'zod';
const connectSchema = z.object({
    token: z.string().regex(/^[\w.-]{50,}$/, 'invalid Discord bot token shape'),
});
async function resolveTenantId(req) {
    const userId = req.user?.id;
    if (!userId)
        return null;
    const { data } = await supabase.from('tenants').select('id').eq('owner_id', userId).maybeSingle();
    return data?.id ?? null;
}
export async function registerDiscordRoutes(app) {
    app.get('/api/channels/discord/status', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req);
        if (!tenantId)
            return reply.status(401).send({ error: 'no tenant' });
        reply.send({ data: getDiscordStatus(tenantId) });
    });
    app.post('/api/channels/discord/connect', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req);
        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 startDiscordSession(tenantId, parsed.data.token);
        if (session.status === 'auth_failed') {
            return reply.status(400).send({ error: `Discord rejected token: ${session.lastError}` });
        }
        reply.send({ data: getDiscordStatus(tenantId) });
    });
    app.post('/api/channels/discord/disconnect', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req);
        if (!tenantId)
            return reply.status(401).send({ error: 'no tenant' });
        await disconnectDiscordSession(tenantId);
        reply.send({ data: { status: 'disconnected' } });
    });
}
//# sourceMappingURL=routes.js.map