import { authMiddleware } from '../../auth/middleware.js';
import { supabase } from '../../utils/supabase.js';
import { startSlackSession, disconnectSlackSession, getSlackStatus } from './adapter.js';
import { z } from 'zod';
const connectSchema = z.object({
    bot_token: z.string().regex(/^xoxb-/, 'bot_token must start with "xoxb-"'),
    app_token: z.string().regex(/^xapp-/, 'app_token must start with "xapp-"'),
});
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 registerSlackRoutes(app) {
    app.get('/api/channels/slack/status', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req);
        if (!tenantId)
            return reply.status(401).send({ error: 'no tenant' });
        reply.send({ data: getSlackStatus(tenantId) });
    });
    app.post('/api/channels/slack/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 startSlackSession(tenantId, parsed.data.bot_token, parsed.data.app_token);
        if (session.status === 'auth_failed') {
            return reply.status(400).send({ error: `Slack rejected token: ${session.lastError}` });
        }
        reply.send({ data: getSlackStatus(tenantId) });
    });
    app.post('/api/channels/slack/disconnect', { preHandler: [authMiddleware] }, async (req, reply) => {
        const tenantId = await resolveTenantId(req);
        if (!tenantId)
            return reply.status(401).send({ error: 'no tenant' });
        await disconnectSlackSession(tenantId);
        reply.send({ data: { status: 'disconnected' } });
    });
}
//# sourceMappingURL=routes.js.map