import Fastify from 'fastify'
import pg from 'pg'

const app = Fastify()
const client = new pg.Client()

app.post('/:subnet/measurement', {
  schema: {
    body: {
      type: 'boolean'
    }
  }
}, async (request, reply) => {
  await client.query(`
    UPDATE stats SET total = total + 1, successful = successful + $1 WHERE subnet = $2
  `, [
    request.body ? 1 : 0,
    request.params.subnet
  ])
  reply.send()
})

app.get('/:subnet', async (request, reply) => {
  const { rows } = await client.query(
    'SELECT total, successful FROM stats WHERE subnet = $1',
    [request.params.subnet]
  )
  reply.send(rows[0])
})

app.listen(8000)