const express = require('express')
const env = require('./config/env')
const { fail } = require('./utils/response')
const requestLogger = require('./middlewares/requestLogger')
const errorHandler = require('./middlewares/errorHandler')
const apiRoutes = require('./routes/apiRoutes')

function createApp() {
    const app = express()

    app.use(express.json({ limit: '1mb' }))
    app.use(requestLogger)

    app.use(env.apiPrefix, apiRoutes)

    app.use((req, res) => {
        return fail(res, 404, 'Route not found', {
            path: req.path,
        })
    })

    app.use(errorHandler)

    return app
}

if (require.main === module) {
    const app = createApp()
    app.listen(env.port, () => {
        console.log(`Server running on port ${env.port}`)
        console.log(`Public base URL: ${env.appBaseUrl}`)
        console.log(`Health check: ${env.appBaseUrl}${env.apiPrefix}/health`)
    })
}

module.exports = {
    createApp,
}