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

import { DatabaseContext } from "~/database/context";
import * as schema from "~/database/schema";
import { expressValueContext } from "~/contexts/express";

export const app = express();

if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is required");

// In dev, ssrLoadModule re-evaluates this file on every request. Cache the
// client on globalThis so HMR re-loads reuse the same connection pool instead
// of leaking a new one each time.
declare global {
  // TypeScript requires `var` in `declare global` blocks — `let`/`const` are not allowed here.
  var __pgClient: ReturnType<typeof postgres> | undefined; // eslint-disable-line no-var
}
const client = (globalThis.__pgClient ??= postgres(process.env.DATABASE_URL));
const db = drizzle(client, { schema });
app.use((_, __, next) => DatabaseContext.run(db, 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;
    },
  }),
);
