// WebSocket for client to receive messages
//import { Server } from 'socket.io';
//import { Client, Notification } from 'pg';
//import { NextResponse } from 'next/server';
//import type { NextRequest } from 'next/server';
//import type { Message } from '~/server/types';

//let isInitialized = false;
//const io = new Server();

//const pgClient = new Client({
  //connectionString: process.env.DATABASE_URL,
//});

//const initializePostgres = async () => {
  //if (isInitialized) return;
  //try {
    //await pgClient.connect();
    //console.log('Connected to PostgreSQL');
    //await pgClient.query('LISTEN new_message');
    
    //pgClient.on('notification', (msg: Notification) => {
      //try {
        //const newMessage: Message = JSON.parse(msg.payload ?? '{}') as Message;
        //const { receiverId, text, id } = newMessage;
        //if (receiverId && typeof receiverId === 'number') {
          //io.to(receiverId.toString()).emit('message', newMessage);
          //console.log(`Message sent to room ${receiverId} with text: ${text}`);
        //} else {
          //console.error('Invalid receiverId:', receiverId);
        //}
      //} catch (error) {
        //console.error('Error parsing notification payload:', error);
      //}
    //});
    //isInitialized = true;
  //} catch (error) {
    //console.error('Error connecting to PostgreSQL:', error);
    //throw error;
  //}
//};

//io.on('connection', (socket) => {
  //console.log('WebSocket client connected', socket.id);

  //socket.on('join', async (userId: number) => {
    //const roomId = userId.toString();
    //await socket.join(roomId);
    //console.log(`WebSocket client joined room ${userId}`);
  //});

  //socket.on('error', (error) => {
    //console.error('WebSocket error:', error);
  //});

  //socket.on('disconnect', () => {
    //console.log('WebSocket client disconnected');
  //});
//});

//export const runtime = 'edge';

//export const GET = async (request: NextRequest) => {
  //try {
    //await initializePostgres();
    //// @ts-expect-error: Socket.IO types conflict with Next.js Request
    //const upgrade = await io.handleUpgrade(request);

    //if (!upgrade || !upgrade.headers)
      //throw new Error('Failed to upgrade connection');

    //return new NextResponse(null, {
      //status: 101,
      //headers: upgrade.headers,
    //});
  //} catch (error) {
    //console.error('Error handling upgrade:', error);
    //return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
  //}
//};
