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

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

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("/api/articles", async (_req: Request, res: Response) => {
	try {
		const response = await fetch("http://localhost:1337/api/articles");

		if (!response.ok) {
			throw new Error(`Strapi API responded with status ${response.status}`);
		}

		const data = await response.json();
		res.json(data); // Pass through Strapi data
	} catch (error) {
		console.error("Error fetching articles from Strapi:", error);
		res.status(500).json({ error: "Failed to fetch data from Strapi" });
	}
});

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

//check and send index ejs
app.get("/", (_req, res) => {
	res.render("index");
});

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