import { data } from "./wwwroot/core/appData.js";
import express from "express";
import {Logger} from "./wwwroot/core/logging/logger.js";
import {launch} from "./bot.js";

await launch();

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

app.get("/oauth/", async (req, res) => {
    const code = req.query.code;
    let resMsg = "";
    try{
        const shortLived = await data.instagramTokenManager.generateShortLivedToken(code);
        const longLived = await data.instagramTokenManager.generateLongLivedToken(shortLived);
        resMsg = "Authentication successful. You can close this tab";
    } catch(err){
        await Logger.error(`Unable to generate token from code ${code}`, err);
        resMsg = "An error occurred. Try again in few minutes.";
    } finally {
        res.send(`
            <html lang="en">
              <head><title>Authentication</title></head>
              <body>${resMsg}</body>
            </html>
        `);
    }
});

app.get("/api/health", (req, res) => {
    res.json({ status: "ok" });
});

app.listen(5004, () => console.log("Node backend listening on port 5004"));
