const WebSocket = require('ws');
const irc = require('irc');

const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', (ws) => {
    console.log('WebSocket client connected');
    ws.on('message', (msg) => {
        try {
            const data = JSON.parse(msg);
            if (data.type === 'connect') {
                console.log('Connect command received:', data);

                const [host, portStr] = (data.server || '').split(':');
                const port = parseInt(portStr) || 6667;
                const nick = data.nick || 'ZeroIRC_guest';
                const channels = data.channels || [];
                const ssl = data.ssl || false;

                console.log(`Connecting to IRC: ${host}:${port} (SSL: ${ssl})`);

                const client = new irc.Client(host, nick, {
                    port,
                    secure: ssl,
                    channels,
                    userName: nick,
                    realName: nick,
                    debug: true,          // shows all IRC traffic
                    retryCount: 0
                });

                const send = (type, payload = {}) => {
                    ws.send(JSON.stringify({ type, ...payload }));
                };

                client.on('registered', () => {
                    console.log('IRC: registered');
                    send('registered');
                });

                client.on('error', (err) => {
                    console.error('IRC Error:', err.message);
                    send('error', { message: err.message });
                });

                client.on('message', (from, to, text) => {
                    send('message', { from, to, text });
                });

                client.on('pm', (from, text) => {
                    send('pm', { from, text });
                });

                client.on('join', (channel, who) => {
                    send('join', { channel, who });
                });

                client.on('part', (channel, who, reason) => {
                    send('part', { channel, who, reason });
                });

                client.on('quit', (who, reason) => {
                    send('quit', { who, reason });
                });

                client.on('kick', (channel, who, by, reason) => {
                    send('kick', { channel, who, by, reason });
                });

                client.on('nick', (old, newNick) => {
                    send('nick', { old, newNick });
                });

                client.on('names', (channel, nicks) => {
                    send('names', { channel, nicks: Object.keys(nicks) });
                });

                client.on('topic', (channel, topic) => {
                    send('topic', { channel, topic });
                });

                client.on('whois', (info) => {
                    send('whois', info);
                });

                client.on('raw', (raw) => {
                    console.log('IRC RAW:', raw.command || raw.rawCommand, raw.args);
                });

            } else if (data.type === 'command' && client) {
                console.log('Command:', data.command, data.args);
                if (client[data.command]) {
                    client[data.command](...data.args);
                } else {
                    client.send(data.command, ...data.args);
                }
            } else if (data.type === 'raw' && client) {
                client.send(data.line);
            }
        } catch (e) {
            console.error('Message handling error:', e);
        }
    });

    ws.on('close', () => {
        console.log('WebSocket closed');
    });
});

console.log('Test gateway listening on port 3000');