import Fastify from 'fastify'
import cors from '@fastify/cors'
import cookie from '@fastify/cookie'
import sensible from '@fastify/sensible'
import { mitraManagementRoutes } from './routes/internal/mitra.routes.js'
import { ccUserRoutes } from './routes/internal/cc-user.routes.js'
import { rolesRoutes } from './routes/internal/roles.routes.js'
import { internalAuthRoutes } from './routes/internal/auth.routes.js'
import { internalConfigRoutes } from './routes/internal/config.routes.js'
import { sessionManagementRoutes } from './routes/internal/session.routes.js'
import { mitraActivityRoutes } from './routes/internal/mitra-activity.routes.js'
import { errorHandler } from './plugins/error-handler.js'

export const buildInternalApp = async () => {
  const app = Fastify({ logger: true })

  // CORS: control center origin must be allowed with credentials for httpOnly refresh cookie
  const ccOrigin = process.env.CC_ORIGIN
  await app.register(cors, {
    origin: ccOrigin ? ccOrigin.split(',').map((s) => s.trim()) : true,
    credentials: true,
  })
  await app.register(cookie)
  await app.register(sensible)
  app.setErrorHandler(errorHandler)

  app.register(internalAuthRoutes, { prefix: '/internal/auth' })
  app.register(mitraManagementRoutes, { prefix: '/internal/mitras' })
  app.register(ccUserRoutes, { prefix: '/internal/control-center-users' })
  app.register(rolesRoutes, { prefix: '/internal/roles' })
  app.register(internalConfigRoutes, { prefix: '/internal/config' })
  app.register(sessionManagementRoutes, { prefix: '/internal/sessions' })
  app.register(mitraActivityRoutes, { prefix: '/internal/mitra-activity' })

  return app
}
