// static variables
import express from "express";
const app = express();
const port = 4000;

// Importing database functions for user operations
import { loginUser, createUser, updateUser, deleteUser } from "./database.js";

// Middleware to parse URL-encoded bodies (form submissions)
app.use(express.urlencoded({ extended: true }));
// Set EJS as the view engine for rendering templates
app.set("view engine", "ejs");

import path from "path";
import { fileURLToPath } from "url";

// Setup for __dirname and __filename in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Start the server and listen on the specified port
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

// Middleware to parse JSON bodies
app.use(express.json());

// Middleware to serve static files from the 'public' directory
app.use(express.static("public"));

// Main code below

// Route to handle GET requests to the root URL (login page)
app.get("/", (req, res) => {
  res.render("login.ejs", { error: null, reload: false });
  console.log("Frontend user requested frontend login page.");
});

// Variable to keep track of the latest logged-in user
let latestUser;

// Route to handle user login
app.post("/login", (req, res) => {
  // Attempt to log in the user with provided credentials
  loginUser(req.body.username, req.body.password).then((result) => {
    if (result.success) {
      // On successful login, render the dashboard and update latestUser
      res.status(200).render("dashboard.ejs", {
        sqlResult: result,
        newLink: `/dashboard/${result.user.id}`,
        alert: null,
        success: null,
      });
      latestUser = result;
    } else {
      // On failure, re-render login page with error message
      res
        .status(401)
        .render("login.ejs", { error: result.message, reload: true });
    }
  });
});

// Route to handle user creation, update, and deletion
app.post(["/createUser", "/updateUser", "/deleteUser"], (req, res) => {
  let action = req.path;
  let funcName;

  // Determine which database function to use based on the route
  if (action === "/createUser") {
    funcName = createUser;
  } else if (action === "/updateUser") {
    funcName = updateUser;
  } else if (action === "/deleteUser") {
    // Prevent deleting the currently logged-in user
    if (latestUser && req.body.username !== latestUser.user.username) {
      funcName = deleteUser;
    } else {
      // Render dashboard with alert if trying to delete logged-in user
      res.status(400).render("dashboard.ejs", {
        sqlResult: latestUser,
        newLink: latestUser ? `/dashboard/${latestUser.id}` : "#",
        alert: "Cannot delete the currently logged-in user!",
        success: null,
      });
      return;
    }
  } else {
    // Handle invalid actions
    res.status(400).send("Invalid action");
    return;
  }
  // Call the selected database function with user data
  funcName(
    req.body.username,
    req.body.first_name,
    req.body.last_name,
    req.body.password,
    req.body.email
  ).then((result) => {
    if (result.success === true) {
      // On success, render dashboard with success message
      res.status(201).render("dashboard.ejs", {
        sqlResult: latestUser,
        newLink: `/dashboard/${latestUser.id}`,
        alert: null,
        success: "User action successful!",
      });
    } else {
      // On failure, render dashboard with alert
      res.status(400).render("dashboard.ejs", {
        sqlResult: latestUser,
        newLink: `/dashboard/${latestUser.id}`,
        alert: "User action failed!",
        success: null,
      });
    }
  });
});

// error handling code
app.use((err, req, res, next) => {
  // Log the error stack and send a generic error response
  console.error(err.stack);
  res.status(500).send("Something broke!");
});
