const express = require("express");
const {RtcTokenBuilder, RtcRole} = require("agora-access-token");
const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

const app = express();

const port = 8080;
const appId = "12994c6e707543e68d5638894d04f989";
const appCertificate = "e21a388f83034a159f2783889a6d7bcf";

app.get("/token", (req, res) => {
  const channelName = req.query.channelName;
  if (!channelName) {
    return res.status(500).json({"error": "channelName is required"});
  }
  let uid = req.query.uid;
  if (!uid) {
    uid = 0;
  }
  let role = RtcRole.SUBSCRIBER;
  if (req.query.role == "publisher") {
    role = RtcRole.PUBLISHER;
  }
  let expireTime = req.query.expireTime;
  if (!expireTime || expireTime == "") {
    expireTime = parseInt(expireTime, 10);
  }
  const currentTime = Math.floor(Date.now() / 1000);
  const privilegeExpireTime = currentTime + expireTime;

  const token = RtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, role, privilegeExpireTime);

  res.json({token});
});

exports.rtcTokenServer = functions.https.onRequest(app);
