import 'dotenv/config'
import { WebSocketServer } from 'ws'
import { initTRPC } from '@trpc/server'
import { createHTTPServer } from '@trpc/server/adapters/standalone'
import { oldServer } from './roleplay/old-server'
import { createRolePlayRouter } from './roleplay/router'
import { createTestsRouter } from './tests/router'
import { createContext, type TrpcContext } from './lib/trpc-context'
import { cors } from './lib/middleware/cors'

const WS_PORT = 8080
const HTTP_PORT = 2022

const wss = new WebSocketServer({ port: WS_PORT })

wss.on('connection', oldServer)

console.log(`WebSocket server started on ws://localhost:${WS_PORT}`)

// ref: https://github.com/trpc/trpc/blob/main/examples/standalone-server/src/server.ts
const t = initTRPC.context<TrpcContext>().create()

const appRouter = t.router({
	agents: createRolePlayRouter(t),
	tests: createTestsRouter(t)
})

export type AppRouter = typeof appRouter

const server = createHTTPServer({
	middleware: cors,
	router: appRouter,
	createContext,
	onError: ({ error }) => {
		console.error(error)
	}
})

server.listen(HTTP_PORT)

console.log(`tRPC server started at http://localhost:${HTTP_PORT}`)

process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)

function shutdown() {
	server.close()
	wss.close()
}
