import { WebSocketServer } from 'ws'
import express from 'express'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { setupWebSocketHandler } from './src/websocket-handler.js'
import { printServerInfo } from './src/server-utils.js'
import { loadState, saveState } from './src/persist.js'
import { listSpotVideos } from './src/spot-utils.js'

const SPOT_DIR = join(dirname(fileURLToPath(import.meta.url)), 'spot')

export default function websocketPlugin() {
  return {
    name: 'vite-plugin-websocket',
    configureServer(server) {
      const wss = new WebSocketServer({ noServer: true })
      setupWebSocketHandler(wss, { initialState: loadState(), onStateChange: saveState })

      // Video spot del time out: stesso comportamento di server.js (elenco + statici)
      server.middlewares.use('/spot', (req, res, next) => {
        if (req.url === '/list' || req.url === '/list/') {
          res.setHeader('Content-Type', 'application/json')
          return res.end(JSON.stringify(listSpotVideos(SPOT_DIR)))
        }
        next()
      })
      server.middlewares.use('/spot', express.static(SPOT_DIR))

      // Rewrite /display → / (index.html) e /controller → /controller.html
      server.middlewares.use((req, _res, next) => {
        if (req.url === '/display' || req.url === '/display/') req.url = '/'
        else if (req.url === '/controller' || req.url === '/controller/') req.url = '/controller.html'
        next()
      })

      server.httpServer.on('upgrade', (request, socket, head) => {
        const pathname = new URL(request.url, `http://${request.headers.host}`).pathname
        if (pathname === '/ws') {
          wss.handleUpgrade(request, socket, head, (ws) => {
            wss.emit('connection', ws, request)
          })
        }
      })

      server.httpServer.once('listening', () => {
        const { port } = server.httpServer.address()
        setTimeout(() => printServerInfo(port), 100)
      })
    }
  }
}
