import dotenv from "dotenv";
dotenv.config({ path: ".env" });

import express, { Application, Request, Response } from "express";
import { marked } from "marked";

const app: Application = express();
const port: number = parseInt(process.env.PORT as string) || 3000;

//Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//Setting up for EJS
app.set("views", `./src/views`);
app.set("view engine", "ejs");

//Get strapi data
app.get("/", async (_req: Request, res: Response) => {
	const postsData = await fetch(
		"http://cms:1337/api/blog-posts?populate=cover_image",
		{
			method: "GET",
			headers: {
				Authorization: `Bearer ${process.env.STRAPI_BEARER_TOKEN}`,
				"Content-Type": "application/json",
			},
		}
	).then((res) => {
		return res.json();
	});

	res.render("index", { posts: postsData });
});

app.get("/post/:slug", async (req: Request, res: Response) => {
	//anything after the colon is a variable. if you go to any website that is
	const postsData = await fetch(
		`http://cms:1337/api/blog-posts?filters[slug]=${req.params.slug}&populate=cover_image`,
		{
			method: "GET",
			headers: {
				Authorization: `Bearer ${process.env.STRAPI_BEARER_TOKEN}`,
			},
		}
	).then((response) => response.json());

	const markedcontent = marked(postsData.data[0].content);

	res.render("post", { post: postsData.data[0], markedcontent });
});

//Static route
app.use(express.static(`${__dirname}/../public`));

app.listen(port, (): void => {
	console.log(`Server is running on port ${port}`);
});
