require("./utils/instrument.js")
const Sentry = require('@sentry/node')

require('dotenv').config()
require('express-async-errors')

const { socketIO } = require('./utils')
const { initIO, getIO } = socketIO

// express 
const express = require('express')
const app = express()
const session = require('express-session')

const bodyParser = require('body-parser') // Para JSON
require('body-parser-xml')(bodyParser)    // Para XML

// rest of the packages
const morgan = require('morgan')
// const fileUpload = require('express-fileupload')

// Middleware para lidar com JSON
app.use(bodyParser.json())

// Middleware para lidar com XML
app.use(bodyParser.xml({
    limit: '1MB',
    xmlParseOptions: {
        explicitArray: false,
    }
}))

const rateLimiter = require('express-rate-limit')

// Swagger
const swaggerUI = require('swagger-ui-express')
const YAML = require('yamljs')
const swaggerDocument = YAML.load('./swagger.yaml')

const helmet = require('helmet')
const xss = require('xss-clean')
const cors = require('cors')

// routers   
const crmRouter = require('./routes/crmRoute')
const integrationRouter = require("./routes/integrationRoutes")

const notFoundMiddlware = require('./middleware/not-found')
const errorHandlerMiddleware = require('./middleware/error-handler')

//middleware
app.set('trust proxy', 1)
app.use(rateLimiter({
    windowMs: 15 * 60 * 1000,
    max: 60,
}))

// Use a session to keep track of client ID
app.use(session({
    secret: Math.random().toString(36).substring(2),
    resave: false,
    saveUninitialized: true
}))

// Security packages
app.use(helmet())
app.use(cors())
app.use(xss())

app.use(morgan('tiny'))
// app.use(express.json())

// app.use(fileUpload())

app.get('/', (req, res) => {
    res.send('<h1>Sentiment API</h1><a href="/api-docs">Documentation</a>')
})

app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocument))

app.use('/api/v1/crm', crmRouter)
app.use('/api/v1/integration', integrationRouter)

Sentry.setupExpressErrorHandler(app)
app.use(notFoundMiddlware)
// app.use(errorHandlerMiddleware)

const port = process.env.PORT || 3000

const server = app.listen(port, console.log(`Listening on port: ${port}...`))

initIO(server)
