import { authMiddleware } from '../auth/middleware.js';
import { createSession, getSession, getTenantSessions, getSessionHistory, processSessionMessage, closeSession, killSession, spawnSubAgent, listSubAgents, steerSubAgent, } from './manager.js';
import { supabase } from '../utils/supabase.js';
// Same fix pattern as cron routes — these endpoints only have
// authMiddleware so request.tenant is never set. Resolve from user.id.
async function resolveOwnerTenant(request) {
    const userId = request.user?.id;
    if (!userId)
        return null;
    const { data } = await supabase
        .from('tenants').select('id').eq('owner_id', userId).limit(1).maybeSingle();
    return data?.id ?? null;
}
export async function registerSessionRoutes(app) {
    // POST /api/sessions — Create new session
    app.post('/api/sessions', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { label, kind, model, thinking, timeoutSeconds, message } = request.body;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        if (!tenantId) {
            return reply.status(401).send({ error: 'Unauthorized' });
        }
        try {
            const session = await createSession({
                tenantId,
                label,
                kind: kind || 'isolated',
                model,
                thinking: thinking || false,
                timeoutSeconds,
                message,
            });
            // If initial message provided, process it
            let output;
            if (message) {
                const result = await processSessionMessage(session.id, message);
                output = result.output;
            }
            reply.send({ success: true, session, output });
        }
        catch (err) {
            reply.status(500).send({ error: err instanceof Error ? err.message : String(err) });
        }
    });
    // GET /api/sessions — List active sessions for tenant
    app.get('/api/sessions', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        const { limit = 20 } = request.query;
        if (!tenantId) {
            return reply.status(401).send({ error: 'Unauthorized' });
        }
        const sessions = await getTenantSessions(tenantId, parseInt(limit));
        reply.send({ sessions });
    });
    // GET /api/sessions/:id — Get session details
    app.get('/api/sessions/:id', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { id } = request.params;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        const session = await getSession(id);
        if (!session || session.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Session not found' });
        }
        reply.send({ session });
    });
    // POST /api/sessions/:id/message — Send message to session
    app.post('/api/sessions/:id/message', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { id } = request.params;
        const { message } = request.body;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        const session = await getSession(id);
        if (!session || session.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Session not found' });
        }
        try {
            const result = await processSessionMessage(id, message);
            reply.send(result);
        }
        catch (err) {
            reply.status(500).send({ error: err instanceof Error ? err.message : String(err) });
        }
    });
    // GET /api/sessions/:id/messages — Get session history
    app.get('/api/sessions/:id/messages', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { id } = request.params;
        const { limit = 50 } = request.query;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        const session = await getSession(id);
        if (!session || session.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Session not found' });
        }
        const messages = await getSessionHistory(id, parseInt(limit));
        reply.send({ messages });
    });
    // POST /api/sessions/:id/close — Close session
    app.post('/api/sessions/:id/close', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { id } = request.params;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        const session = await getSession(id);
        if (!session || session.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Session not found' });
        }
        await closeSession(id);
        reply.send({ success: true });
    });
    // POST /api/sessions/:id/kill — Kill session
    app.post('/api/sessions/:id/kill', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { id } = request.params;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        const session = await getSession(id);
        if (!session || session.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Session not found' });
        }
        await killSession(id);
        reply.send({ success: true });
    });
    // POST /api/sessions/spawn — Spawn sub-agent
    app.post('/api/sessions/spawn', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { label, kind, model, thinking, timeoutSeconds, message } = request.body;
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        if (!tenantId || !message) {
            return reply.status(400).send({ error: 'Missing required fields: tenantId, message' });
        }
        try {
            const result = await spawnSubAgent({
                tenantId,
                label,
                kind: kind || 'isolated',
                model,
                thinking: thinking || false,
                timeoutSeconds,
                message,
            });
            reply.send(result);
        }
        catch (err) {
            reply.status(500).send({ error: err instanceof Error ? err.message : String(err) });
        }
    });
    // GET /api/sessions/subagents — List sub-agents
    app.get('/api/sessions/subagents', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const tenantId = request.tenant?.id ?? await resolveOwnerTenant(request);
        if (!tenantId) {
            return reply.status(401).send({ error: 'Unauthorized' });
        }
        const agents = await listSubAgents(tenantId);
        reply.send({ subagents: agents });
    });
    // POST /api/sessions/steer — Send message to existing sub-agent
    app.post('/api/sessions/steer', {
        preHandler: [authMiddleware],
    }, async (request, reply) => {
        const { sessionId, message } = request.body;
        if (!sessionId || !message) {
            return reply.status(400).send({ error: 'Missing required fields: sessionId, message' });
        }
        try {
            const result = await steerSubAgent(sessionId, message);
            reply.send(result);
        }
        catch (err) {
            reply.status(500).send({ error: err instanceof Error ? err.message : String(err) });
        }
    });
}
//# sourceMappingURL=routes.js.map