"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const socket_io_1 = require("socket.io");
const http_1 = require("http");
const pg_1 = require("pg");
const dotenv_1 = __importDefault(require("dotenv"));
dotenv_1.default.config();
const app = (0, express_1.default)();
const httpServer = (0, http_1.createServer)(app);
// Create new Socket.IO server
const io = new socket_io_1.Server(httpServer);
const PORT = process.env.PORT || 3030;
const pgClient = new pg_1.Client({
    connectionString: process.env.DATABASE_URL,
});
const handleNotification = (msg) => {
    var _a;
    const payload = JSON.parse((_a = msg.payload) !== null && _a !== void 0 ? _a : '{}');
    switch (msg.channel) {
        case 'new_message':
            handleNewMessage(payload);
            break;
        case 'countdown_update':
            handleCountdownUpdate(payload);
            break;
        case 'relationship_status_change':
            handleRelationshipStatusChange(payload);
            break;
        case 'profile_picture_update':
            handleProfilePictureUpdate(payload);
            break;
        default:
            console.log('Unhandled notification:', msg);
    }
};
const handleNewMessage = (payload) => {
    const { receiverId, text, id } = payload;
    io.to(`user:${receiverId}`).emit('new_message', payload);
    console.log(`Message sent to room ${receiverId} with text: "${text}"`);
};
const handleCountdownUpdate = (payload) => {
    const { relationshipId, countdown } = payload;
    io.to(`relationship:${relationshipId}`).emit('countdown_update', countdown);
    console.log(`Countdown update sent to room ${relationshipId}`);
};
const handleRelationshipStatusChange = (payload) => {
    const { relationshipId, status } = payload;
    io.to(`relationship:${relationshipId}`).emit('relationship_status_change', status);
    console.log(`Relationship status change sent to room ${relationshipId}, status: ${status}`);
};
const handleProfilePictureUpdate = (payload) => {
    const { userId, profilePictureUrl } = payload;
    io.to(`user:${userId}`).emit('profile_picture_update', profilePictureUrl);
    console.log(`Profile picture update sent to room ${userId}`);
};
// Connect the PostgreSQL client
pgClient.connect()
    .then(() => {
    console.log('Connected to PostgreSQL');
    // Listen for NOTIFY events on the 'new_message' channel
    pgClient.query('LISTEN new_message');
    pgClient.query('LISTEN countdown_update');
    pgClient.query('LISTEN relationship_status_change');
    pgClient.query('LISTEN profile_picture_update');
    pgClient.on('notification', handleNotification);
})
    .catch((err) => {
    console.error('Failed to connect to PostgreSQL:', err);
});
// Handle WebSocket connections
io.on('connection', (socket) => {
    console.log('WebSocket client connected:', socket.id);
    socket.on('join', (roomInfo) => {
        //console.log('Attempting to join room:', roomInfo);
        if (typeof roomInfo === 'object') {
            if (roomInfo.userId) {
                socket.join(`user:${roomInfo.userId}`);
                console.log(`User ${roomInfo.userId} joined room`);
            }
            else if (roomInfo.relationshipId) {
                socket.join(`relationship:${roomInfo.relationshipId}`);
                console.log(`Relationship ${roomInfo.relationshipId} joined room`);
            }
        }
        //console.log('Socket object at connection:', socket);
    });
    socket.on('error', (error) => {
        console.error('WebSocket error:', error);
    });
    // Handle disconnection of WebSocket clients
    socket.on('disconnect', () => {
        console.log('WebSocket client disconnected:', socket.id);
    });
});
// Start the WebSocket server
httpServer.listen(PORT, () => {
    console.log(`WebSocket server is running on port ${PORT}`);
});
