const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const webpush = require('web-push')
const cors = require('cors')
const config = require('config')

mongoose.connect(config.get('DB_URL'))
const Schema = mongoose.Schema
const subSchema = Schema({
  userId: String,
  storeId: String,
  endpoint: String,
  publicKey: String,
  auth: String,
})
const Subscribe = mongoose.model('Subscribe', subSchema)

const app = express()
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))

const vapidKeys = {
  publicKey: config.get('PUBLIC_KEY'),
  privateKey: config.get('SECRET_KEY')
}

webpush.setVapidDetails(
  'localhost:8000',
  vapidKeys.publicKey,
  vapidKeys.privateKey
)

app.get('/status', (req, res) => {
  res.send('Server is running')
})

app.get('/subscribe', (req, res) => {
  Subscribe.find({})
  .then(data => res.send(data))
  .catch(error => res.send(error))
})

app.post('/subscribe', (req, res) => {
  const newSubscriber = {
    endpoint: req.body.endpoint,
    keys: {
      p256dh: req.body.publicKey,
      auth: req.body.auth
    }
  }

  const { storeId, userId } = req.body
   
  Subscribe.update(
    { userId, storeId },
    {
      storeId,
      userId,
      endpoint: req.body.endpoint,
      publicKey: req.body.publicKey,
      auth: req.body.auth
    },
    { upsert: true } 
  )
  .then(() => { 
    res.send({ success: true, message: 'add success' })    
  })
  .catch(e => {
    res.send({ success: false, message: 'something worng' })
  })
})


const PORT = process.env.PORT || 8080;
app.listen(PORT, function () {
  console.log(`push_server listening on port ${PORT}!`)
})



@@ -852,32 +852,37 @@
 .get('/subscribe
+/list
 ', (req, res) =%3E
@@ -972,24 +972,250 @@
 error))%0A%7D)%0A%0A
+app.get('/subscribe/check', (req, res) =%3E %7B%0A  const %7B storeId, userId %7D = req.body  %0A  Subscribe.find(%7B storeId, userId %7D)%0A  .then(sub =%3E %7B%0A    if (sub) %7B%0A      res.send(true)%0A    %7D else %7B%0A      res.send(false)%0A    %7D%0A  %7D)%0A%7D)%0A%0A
 app.post('/s

add check sub for server