"use strict";

const express = require("express");
const fs = require("fs");
const { tokenGenerate } = require("@vonage/jwt");
const privateKey = fs.readFileSync("gh-private.key");
const aclPaths = {
	paths: {
		"/*/rtc/**": {},
		"/*/users/**": {},
		"/*/conversations/**": {},
		"/*/sessions/**": {},
		"/*/devices/**": {},
		"/*/image/**": {},
		"/*/media/**": {},
		"/*/knocking/**": {},
		"/*/legs/**": {},
	},
};

const app = express();
app.use(express.json());

const vonageNumber = "12052553394"; //用于通话的号码，今后根据前端提交来做号码切换

//设置跨域访问
app.all("*", function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "*");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});

app.get("/voice/answer", (req, res) => {
	console.log("NCCO request:");
	console.log(`  - callee: ${req.query.to}`);
	console.log("---");
	res.json([
		{
			action: "talk",
			text: "Please wait while we connect you.",
		},
		{
			action: "record",
			eventUrl: [`${req.protocol}://${req.get("host")}/vonage-server/voice/recordings`],
		},
		{
			action: "connect",
			from: vonageNumber,
			endpoint: [{ type: "phone", number: req.query.to }],
		},
	]);
});

app.get("/jwt", (req, res) => {
	console.log("jwt  Generate:");
	const exp_time = new Date(Date.now() + 3 * 24 * 3600 * 1000);
	const token = tokenGenerate("39f32a2a-e343-4ca0-9d92-5946573af5ea", privateKey, {
		exp: Math.round(exp_time.getTime() / 1000),
		sub: "hainatravel",
		acl: aclPaths,
	});
	console.log(Math.round(exp_time.getTime() / 1000));
	console.log(token);
	console.log("---");
	res.json({
		token: token,
		status: 200,
	});
});

app.all("/voice/event", (req, res) => {
	console.log("EVENT:");
	console.dir(req.body);
	console.log("---");
	res.sendStatus(200);
});

app.all("/voice/fallback", (req, res) => {
	console.log("fallback:");
	console.dir(req.body);
	console.dir(res);
	console.log("---");
	res.sendStatus(200);
});

app.all("/voice/recordings", (req, res) => {
	console.log("recordings:");
	console.dir(req.body);
	res.sendStatus(200);
});

app.listen(3009);
