import { Router } from 'express';
import { eq } from 'drizzle-orm';
import { getDatabase } from '../services/database.js';
import { windows } from '../schema.js';
import { setupSSE, sendSSE, addWindowClient, removeWindowClient, broadcastWindowEvent, } from '../services/sse-manager.js';
const router = Router();
// SSE endpoint for window sync
router.get('/events', (req, res) => {
    const clientId = req.headers['x-client-id'];
    const client = setupSSE(res, clientId);
    sendSSE(client, { type: 'connected' });
    addWindowClient(client);
    req.on('close', () => removeWindowClient(client));
});
// List all windows
router.get('/windows', async (_req, res) => {
    try {
        const db = await getDatabase();
        const allWindows = db.select().from(windows).orderBy(windows.createdAt).all();
        res.json(allWindows);
    }
    catch (err) {
        console.error('[windows] Failed to list windows:', err);
        res.status(500).json({ error: 'Failed to list windows' });
    }
});
// Create a new window
router.post('/windows', async (req, res) => {
    try {
        const db = await getDatabase();
        const clientId = req.headers['x-client-id'];
        const body = req.body;
        if (!body.id || !body.directoryId || !body.createdAt) {
            res.status(400).json({ error: 'Missing required fields: id, directoryId, createdAt' });
            return;
        }
        const newWindow = {
            id: body.id,
            directoryId: body.directoryId,
            rootSessionId: body.rootSessionId ?? null,
            activeSessionId: body.activeSessionId ?? null,
            lastActiveAt: body.lastActiveAt ?? body.createdAt, // Default to createdAt
            agent: body.agent ?? null,
            modelProvider: body.modelProvider ?? null,
            modelId: body.modelId ?? null,
            label: body.label ?? null,
            createdAt: body.createdAt,
        };
        db.insert(windows).values(newWindow).run();
        const created = db.select().from(windows).where(eq(windows.id, body.id)).get();
        broadcastWindowEvent({ type: 'window:created', window: created, sourceClientId: clientId });
        res.json(created);
    }
    catch (err) {
        console.error('[windows] Failed to create window:', err);
        res.status(500).json({ error: 'Failed to create window' });
    }
});
// Update a window
router.patch('/windows/:id', async (req, res) => {
    try {
        const db = await getDatabase();
        const clientId = req.headers['x-client-id'];
        const windowId = req.params.id;
        const body = req.body;
        // Check if window exists
        const existing = db.select().from(windows).where(eq(windows.id, windowId)).get();
        if (!existing) {
            res.status(404).json({ error: 'Window not found' });
            return;
        }
        // directoryId is immutable - reject any attempt to change it
        if (body.directoryId !== undefined) {
            res.status(400).json({ error: 'directoryId cannot be changed after window creation' });
            return;
        }
        // Build update object (only include provided fields)
        const updates = {};
        if (body.rootSessionId !== undefined)
            updates.rootSessionId = body.rootSessionId;
        if (body.activeSessionId !== undefined)
            updates.activeSessionId = body.activeSessionId;
        if (body.lastActiveAt !== undefined)
            updates.lastActiveAt = body.lastActiveAt;
        if (body.agent !== undefined)
            updates.agent = body.agent;
        if (body.modelProvider !== undefined)
            updates.modelProvider = body.modelProvider;
        if (body.modelId !== undefined)
            updates.modelId = body.modelId;
        if (body.label !== undefined)
            updates.label = body.label;
        if (Object.keys(updates).length > 0) {
            db.update(windows).set(updates).where(eq(windows.id, windowId)).run();
        }
        const updated = db.select().from(windows).where(eq(windows.id, windowId)).get();
        broadcastWindowEvent({ type: 'window:updated', window: updated, sourceClientId: clientId });
        res.json(updated);
    }
    catch (err) {
        console.error('[windows] Failed to update window:', err);
        res.status(500).json({ error: 'Failed to update window' });
    }
});
// Delete a window
router.delete('/windows/:id', async (req, res) => {
    try {
        const db = await getDatabase();
        const clientId = req.headers['x-client-id'];
        const windowId = req.params.id;
        const existing = db.select().from(windows).where(eq(windows.id, windowId)).get();
        if (!existing) {
            res.status(404).json({ error: 'Window not found' });
            return;
        }
        db.delete(windows).where(eq(windows.id, windowId)).run();
        broadcastWindowEvent({ type: 'window:deleted', windowId, sourceClientId: clientId });
        res.json({ ok: true });
    }
    catch (err) {
        console.error('[windows] Failed to delete window:', err);
        res.status(500).json({ error: 'Failed to delete window' });
    }
});
export default router;
