const express = require('express')
const next = require('next')
const compression = require('compression')

const port = process.env.PORT || 3001
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  if (!dev) {
    server.use(compression())
  }

  server.get('/awtis', (request, response) => {
    response.redirect('/awtis/paj/1')
  })

  server.get('/awtis/paj/:paj', (request, response) => {
    app.render(request, response, '/awtis', {
      ...request.query,
      paj: request.params.paj
    })
  })

  server.get('*', (request, response) => handle(request, response))

  server.post('*', (request, response) => handle(request, response))

  server.listen(port, error => {
    if (error) {
      throw error
    }
  })

  console.log(`> Ready on http://localhost:${port}`)
})
