import Fastify from 'fastify'
import cors from '@fastify/cors'
import sensible from '@fastify/sensible'
import { sharedAuthRoutes } from './routes/public/shared.auth.routes.js'
import { clientAuthRoutes } from './routes/public/client.auth.routes.js'
import { mitraAuthRoutes } from './routes/public/mitra.auth.routes.js'
import { sharedConfigRoutes } from './routes/public/shared.config.routes.js'
import { mitraStatusRoutes } from './routes/public/mitra.status.routes.js'
import { mitraChatRoutes } from './routes/public/mitra.chat.routes.js'
import { clientChatRoutes } from './routes/public/client.chat.routes.js'
import { sharedChatRoutes } from './routes/public/shared.chat.routes.js'
import { errorHandler } from './plugins/error-handler.js'
import { registerWebSocketPlugin, registerWebSocketRoute } from './plugins/websocket.js'

export const buildPublicApp = async () => {
  const app = Fastify({ logger: true, trustProxy: true })

  await app.register(cors, { origin: true })
  await app.register(sensible)
  await registerWebSocketPlugin(app)
  app.setErrorHandler(errorHandler)

  app.register(sharedAuthRoutes, { prefix: '/api/shared/auth' })
  app.register(sharedConfigRoutes, { prefix: '/api/shared/config' })
  app.register(sharedChatRoutes, { prefix: '/api/shared' })
  app.register(clientAuthRoutes, { prefix: '/api/client/auth' })
  app.register(mitraAuthRoutes, { prefix: '/api/mitra/auth' })
  app.register(mitraStatusRoutes, { prefix: '/api/mitra/status' })
  app.register(mitraChatRoutes, { prefix: '/api/mitra/chat-requests' })
  app.register(clientChatRoutes, { prefix: '/api/client/chat' })

  // WebSocket route (registered at app level, not prefixed)
  registerWebSocketRoute(app)

  return app
}
