import { Server } from 'socket.io'
import { createServer } from 'http'
import { parse } from 'url'
import next from 'next'
import { prisma } from '@/lib/db'

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

let io: Server

export function initializeWebSocket(server: any) {
  io = new Server(server, {
    cors: {
      origin: process.env.NEXTAUTH_URL || 'http://localhost:3000',
      methods: ['GET', 'POST']
    }
  })

  io.on('connection', (socket) => {
    console.log('Client connected:', socket.id)

    // Join prayer room
    socket.on('join-prayer-room', () => {
      socket.join('prayers')
      console.log(`Socket ${socket.id} joined prayer room`)
    })

    // Handle new prayer
    socket.on('new-prayer', async (data) => {
      console.log('New prayer received:', data)
      // Broadcast to all in prayer room
      io.to('prayers').emit('prayer-added', data)
    })

    // Handle prayer count update
    socket.on('pray-for', async (requestId) => {
      try {
        // Get client IP (simplified for development)
        const clientIP = socket.handshake.address || 'unknown'

        // Check if already prayed
        const existingPrayer = await prisma.prayer.findUnique({
          where: {
            requestId_ipAddress: {
              requestId,
              ipAddress: clientIP
            }
          }
        })

        if (!existingPrayer) {
          // Add new prayer
          await prisma.prayer.create({
            data: {
              requestId,
              ipAddress: clientIP
            }
          })

          // Update prayer count
          const updatedRequest = await prisma.prayerRequest.update({
            where: { id: requestId },
            data: {
              prayerCount: {
                increment: 1
              }
            }
          })

          // Broadcast updated count
          io.to('prayers').emit('prayer-count-updated', {
            requestId,
            count: updatedRequest.prayerCount
          })
        }
      } catch (error) {
        console.error('Error updating prayer count:', error)
      }
    })

    socket.on('disconnect', () => {
      console.log('Client disconnected:', socket.id)
    })
  })

  return io
}

export function getSocketIO() {
  return io
}

// Start server if running this file directly
if (require.main === module) {
  app.prepare().then(() => {
    const server = createServer((req, res) => {
      const parsedUrl = parse(req.url!, true)
      handle(req, res, parsedUrl)
    })

    initializeWebSocket(server)

    const port = process.env.WEBSOCKET_PORT || 3015
    server.listen(port, () => {
      console.log(`WebSocket server running on port ${port}`)
    })
  })
}