import express from 'express'
import SMS from '../models/sms'
import bulksms from '../config/bulksms'
import base64 from 'base-64'
import fetch from 'node-fetch'

const sms = express.Router() 

sms.post('/send', async (req, res) => {
    try {
        const { recipients, body, sender } = req.body
        const Authorization = `Basic ${base64.encode(`${bulksms.tokenId}:${bulksms.tokenSecret}`)}`
        const response = await fetch(`https://api.bulksms.com/v1/messages`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization
            },
            body: JSON.stringify({
                to: recipients,
                from: sender,
                body
            })
        })
        const responseContent = (response.status == 201) ?
            await response.json() :
            await response.text()
        const dbSMS = new SMS({
            sent: new Date(),
            body,
            recipients,
            sender,
            response: (response.status == 201) ? JSON.stringify(responseContent) : responseContent
        })
        dbSMS.save()
        if (response.status != 201) {
            throw Error(responseContent)
        }
        res.json(responseContent)
    } catch (error) {
        return res.status(400).json({ msg: error.toString() })
    }
})

sms.get('/credits', async (req, res) => {
    try {
        const Authorization = `Basic ${base64.encode(`${bulksms.tokenId}:${bulksms.tokenSecret}`)}`
        const response = await fetch(`https://api.bulksms.com/v1/profile`, {
            method: 'GET',
            headers: {
                Authorization
            }
        })
        if (response.status != 200) {
            throw Error(`Received status code ${response.status}`)
        }
        const responseJson = await response.json()
        res.json(responseJson.credits.balance)
    } catch (error) {
        return res.status(400).json({ msg: error.toString() })
    }
})

export default sms