import { createRequestHandler } from "@react-router/express";
import express from "express";
import type { ServerBuild } from "react-router";
import { RouterContextProvider } from "react-router";

import { DatabaseContext } from "~/database/context";
import { db } from "./db";
import { expressValueContext } from "~/contexts/express";

export const app = express();

app.use((_, __, next) => DatabaseContext.run(db, next));

// Block common bot probe paths before React Router (and Sentry) see them
const BOT_PROBE_RE =
  /\.(php|env|htaccess|aspx|asp|jsp|config|bak|sql|ini|swp|DS_Store)$|^\/(wp-admin|wp-login|phpmyadmin|xmlrpc|server-status|cgi-bin|shell|cmd|console|actuator)(\/|$)/i;

app.use((req, res, next) => {
  if (BOT_PROBE_RE.test(req.path)) {
    res.status(404).end();
    return;
  }
  next();
});

app.use(
  createRequestHandler({
    build: () => import("virtual:react-router/server-build") as unknown as Promise<ServerBuild>,
    // @ts-ignore -- RouterContextProvider is the correct runtime type but tsconfig.server.json can't resolve the conditional type statically
    getLoadContext() {
      const provider = new RouterContextProvider();
      provider.set(expressValueContext, "Hello from Express");
      return provider as unknown as RouterContextProvider;
    },
  }),
);
