const fastify = require("fastify")({
  logger: { level: "error" },
});

const path = require("path");
const jwt = require("jsonwebtoken");
const { initHeadless } = require("./electron/shared/headless");
const { initDatabase } = require("./electron/shared/database");
const { loadExtensions } = require("./electron/shared/extensions");
const dotenv = require("dotenv");
const envPath = process.resourcesPath
  ? path.join(process.resourcesPath, ".env")
  : path.join(__dirname, ".env");

// Attempt to load it and log the result to be sure
dotenv.config({ path: envPath });

const viewsRoutes = require("./electron/views/views.routes");
const animeRoutes = require("./electron/api/anime/anime.routes");
const booksRoutes = require("./electron/api/books/books.routes");
const proxyRoutes = require("./electron/api/proxy/proxy.routes");
const extensionsRoutes = require("./electron/api/extensions/extensions.routes");
const galleryRoutes = require("./electron/api/gallery/gallery.routes");
const userRoutes = require("./electron/api/user/user.routes");
const listRoutes = require("./electron/api/list/list.routes");
const anilistRoute = require("./electron/api/anilist/anilist");

fastify.addHook("preHandler", async (request) => {
  const auth = request.headers.authorization;
  if (!auth) return;

  try {
    const token = auth.replace("Bearer ", "");
    request.user = jwt.verify(token, process.env.JWT_SECRET);
  } catch (e) {
    return reply.code(401).send({ error: "Invalid token" });
  }
});

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "public"),
  prefix: "/public/",
  decorateReply: false,
});

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "views"),
  prefix: "/views/",
  decorateReply: false,
});

fastify.register(require("@fastify/static"), {
  root: path.join(__dirname, "src", "scripts"),
  prefix: "/src/scripts/",
  decorateReply: false,
});

fastify.register(viewsRoutes);
fastify.register(animeRoutes, { prefix: "/api" });
fastify.register(booksRoutes, { prefix: "/api" });
fastify.register(proxyRoutes, { prefix: "/api" });
fastify.register(extensionsRoutes, { prefix: "/api" });
fastify.register(galleryRoutes, { prefix: "/api" });
fastify.register(userRoutes, { prefix: "/api" });
fastify.register(anilistRoute, { prefix: "/api" });
fastify.register(listRoutes, { prefix: "/api" });

const start = async () => {
  try {
    initDatabase("anilist");
    initDatabase("favorites");
    initDatabase("cache");
    initDatabase("userdata");

    await loadExtensions();

    await fastify.listen({ port: 54322, host: "0.0.0.0" });
    console.log(`Server is now running!`);

    await initHeadless();
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();
