import express from 'express';
import { v4 as uuidv4 } from 'uuid';
import { sessions, SessionState, broadcastToSession, handleWebSocketMessage } from '../ws'; // Import sessions, SessionState, broadcastToSession, and handleWebSocketMessage from ws/index.ts

const router = express.Router();

router.post('/sessions', (req, res) => {
    const sessionId = uuidv4();
    sessions.set(sessionId, {
        state: SessionState.SETUP,
        topic: null,
        description: null,
        expectedResponses: 0,
        submittedCount: 0,
        responses: new Map(),
        clients: new Map(),
        finalResult: null,
    });
    res.status(201).json({ sessionId });
});

router.post('/sessions/:sessionId/responses', async (req, res) => {
    const { sessionId } = req.params;
    const { userId, wants, accepts, afraidToAsk } = req.body;

    if (!sessions.has(sessionId)) {
        return res.status(404).json({ message: 'Session not found.' });
    }

    // Create a dummy WebSocket object for the handleWebSocketMessage function.
    // This is a workaround to reuse the WebSocket message handling logic.
    // In a real application, consider a more robust event-driven architecture.
    const dummyWs: any = {
        send: (message: string) => console.log('Dummy WS send:', message),
        readyState: 1, // OPEN
    };

    const message = {
        type: 'SUBMIT_RESPONSE',
        clientId: userId, // Using userId as clientId for simplicity in this context
        payload: {
            response: { wants, accepts, afraidToAsk },
        },
    };

    try {
        await handleWebSocketMessage(dummyWs, sessionId, message);
        res.status(202).json({ message: 'Response submission acknowledged and processed.' });
    } catch (error: any) {
        console.error('Error processing response via HTTP route:', error);
        res.status(500).json({ message: 'Error processing response.', error: error.message });
    }
});

router.get('/sessions/:sessionId/results', (req, res) => {
    const { sessionId } = req.params;

    if (!sessions.has(sessionId)) {
        return res.status(404).json({ message: 'Session not found.' });
    }

    const sessionData = sessions.get(sessionId)!;

    if (sessionData.state !== SessionState.FINAL || !sessionData.finalResult) {
        return res.status(200).json({ message: 'Session results not yet finalized.', harmonizedIdeas: [] });
    }

    // Assuming finalResult directly contains the harmonized ideas as per openapi.yaml
    res.status(200).json({ sessionId, harmonizedIdeas: sessionData.finalResult });
});

router.post('/sessions/:sessionId/terminate', (req, res) => {
    const { sessionId } = req.params;

    if (!sessions.has(sessionId)) {
        return res.status(404).json({ message: 'Session not found.' });
    }

    sessions.delete(sessionId);
    // Log the purging event
    // logEvent('session_terminated_and_purged', sessionId);
    console.log(`Session ${sessionId} terminated and data purged.`);
    res.status(200).json({ message: 'Session terminated and data purged successfully.' });
});

export default router;