import "reflect-metadata";
import express, { NextFunction, Request, Response } from "express";
import dotenv from "dotenv";
import { AppDataSource } from "./data-source.js";
import authRoutes, { authBasicRoute } from "./endpoints/AuthPoint.js";
import userRoutes from "./endpoints/UserPoint.js";
// import recipeRoutes from "./endpoints/RecipePoint.js";
import { errorHandler } from "./middleware/errorHandler.js";
import { authentication } from "./middleware/authenticationMiddleware.js";

dotenv.config();

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

async function startServer() {
  try {
    // Initialize database
    await AppDataSource.initialize();
    console.log("Data Source initialized");

    // Run pending migrations
    await AppDataSource.runMigrations();
    console.log("Migrations executed");

    // Activate Authentication
    app.use(authentication);

    // Setup routes
    app.use(authBasicRoute, authRoutes);
    app.use("/user", userRoutes);
    // app.use("/recipe", recipeRoutes);

    // Error handling for all rest-calls 
    // must come last!
    app.use(errorHandler);

    console.log("auth and user routes added")
    // catch all other routes
    app.get(/(.*)/, (req: Request, res: Response, next: NextFunction) => {
      res.status(400).json({ message: "Bad Request" });
    });
    console.log("Routes set up")

    // Start listening
    const PORT = Number(process.env.PORT) || 4000;
    const HOST = process.env.HOST || "localhost";

    app.listen(PORT, HOST, () => {
      console.log(`✅ Server running on http://${HOST}:${PORT}`);
    });
  } catch (err) {
    console.error("❌ Error during Data Source initialization:", err);
    process.exit(1);
  }
}

// Call the async start function
startServer();
