const PORT = 8000;
const express = require("express");
const cors = require("cors");
const axios = require("axios");
require("dotenv").config();

const app = express();

app.use(cors());
app.use(express.json());

app.get("/", cors(), async (req, res) => {
	res.json("nothing here");
});

app.post("/post-statistics", cors(), async (req, res) => {
	const WORDPRESS_STATS_USERNAME = process.env.REACT_APP_WORDPRESS_STATS_USERNAME;
	const WORDPRESS_STATS_PASSWORD = process.env.REACT_APP_WORDPRESS_STATS_PASSWORD;
	const WORDPRESS_GET_TOKEN_URL = process.env.REACT_APP_WORDPRESS_GET_TOKEN_URL;
	const WORDPRESS_POST_STATS_URL = process.env.REACT_APP_WORDPRESS_POST_STATS_URL;

	try {
		// ##### GET TOKEN
		const tokenResponse = await axios.post(WORDPRESS_GET_TOKEN_URL, {
			username: WORDPRESS_STATS_USERNAME,
			password: WORDPRESS_STATS_PASSWORD,
		});

		const token = tokenResponse.data.token;

		const requestDataExample = req.body;

		const secondResponse = await axios({
			method: "POST",
			url: WORDPRESS_POST_STATS_URL,
			headers: { Authorization: `Bearer ${token}` },
			data: requestDataExample,
		});

		// ##### RETURN SUCCESS
		res.json(secondResponse.data);
	} catch (error) {
		console.error(error);
		res.status(500).send("An error occurred");
	}
});

app.listen(PORT, () => {
	console.log(`Backend is running on port ${PORT}`);
});
