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

const port = process.env.PORT || 3000
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(
    '/service-worker.js',
    express.static(path.join(process.cwd(), '.next'))
  )

  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) => {
    return handle(request, response)
  })

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

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

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