import webpush from 'web-push';
import { Router } from 'express';
import { v4 } from 'uuid';

const app = Router();


webpush.setVapidDetails(
    'mailto:gstefan1995@gmail.com',
    'BP62v95jRlEXxPlR3EbZ3hTgxpiLXmr-1_jGvLt3z8BKmLRcbSZideBoqEVqWLcs4oPDVn-nvhif659-vNHqk6A',
    'Kk-aCCrXBl4WxUnzZD1Uwr8ImtPXu5uqEZnghyqgu7I'
);

const serverName = process.env.SERVER_NAME || 'http://localhost:3000';

const pushData = new Map();

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});

app.options('/push', (req, res) => {
    res.header('Access-Control-Allow-Methods', 'POST');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.send();
});

app.post('/push', async (req, res) => {
    try {
        console.log(JSON.stringify(req.body));
        const uuid = v4();
        pushData.set(uuid, req.body.message);
        setTimeout(() => {
            pushData.delete(uuid);
        }, 10 * 60 * 1000);
        await webpush.sendNotification(req.body.subscription, JSON.stringify({ url: serverName + '/pushdata?uuid=' + uuid }));
        res.send('ok');
    } catch (err: any) {
        console.error(err);
        if (err.statusCode) {
            res.status(err.statusCode);
        } else {
            res.status(500);
        }
        res.send(JSON.stringify(err));
    }
});

app.get('/pushdata', async (req, res) => {
    try {
        const uuid = req.query.uuid;
        const data = pushData.get(uuid);
        if (!data) {
            res.status(404).send('Not found');
            return;
        }
        res.status(200).send(data);
    } catch (err: any) {
        console.error(err);
        if (err.statusCode) {
            res.status(err.statusCode);
        } else {
            res.status(500);
        }
        res.send(JSON.stringify(err));
    }
})

export default app;