import { createReadStream, existsSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { type Request, type Response, Router } from 'express';
import type { AuthService } from '../auth/auth.service';

/** Shown to the operator when the file never reached the host — the one thing
 *  that can go wrong here, and a stack trace would not say which. */
const NOT_DEPLOYED = 'The user manual was not deployed with this server';

/** Where the manual is at runtime. `npm run build -w @rms/api` copies it next to
 *  the compiled server (scripts/copy-manual.mjs), because the host gets
 *  apps/api/dist and no docs/ folder. The repo copy is only a second candidate
 *  so `nest start --watch` — which compiles but never runs the build script —
 *  and the smoke serve the real document instead of a 404 nobody can explain.
 *  Both this file and its compiled twin sit one level under src/ or dist/, so
 *  four levels up is the repo root either way. */
const MANUAL_CANDIDATES: readonly string[] = [
  join(__dirname, '..', 'user-manual.html'),
  join(__dirname, '..', '..', '..', '..', 'docs', 'user-manual.html'),
];

/**
 * Raw Express route for the office's user manual — one 5 MB HTML file with its
 * screenshots inlined, so tRPC (JSON-only) is the wrong pipe, exactly as for
 * uploads and generated PDFs. Mounted at /api/manual from main.ts.
 *
 * It is a route rather than a file under the SPA's dist/ because the screenshots
 * show the twenty real landlord companies and their accounting codes: a static
 * file is world-readable to anyone who guesses the path.
 *
 * `candidates` is overridden only by the smoke, which has to prove a missing
 * file changes nothing about how the refusals read.
 */
export function createManualRouter(authService: AuthService, candidates: readonly string[] = MANUAL_CANDIDATES) {
  const router = Router();

  // GET /api/manual  → the back-office manual, for any staff login
  router.get('/', async (req: Request, res: Response) => {
    // Bearer only, like the documents adapter: the client fetches the bytes and
    // hands the viewer a blob URL, so no token ever lands in a URL — which is
    // browser history, referrers and every proxy log along the way.
    const header = req.headers.authorization;
    const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
    const user = token ? await authService.verifyAndLoad(token) : null;
    if (!user) return res.status(401).json({ error: 'Unauthorized' });
    // No permission key. Everyone in the office needs the manual, a read-only
    // role included — it is documentation, not data, and a permission nobody
    // would ever withhold is a checkbox that only generates support calls. The
    // lines worth drawing are the two staffProcedure draws, in its order and
    // with its wording: a password somebody else chose is a credential that was
    // read out over the phone and is not yet the holder's own, and this is the
    // BACK OFFICE manual, so a portal login is not back office. Neither costs a
    // staff member anything — the admin shell shows the forced-password screen
    // INSTEAD of the sidebar, so no one who can click the entry is refused here.
    if (user.mustChangePassword) {
      return res.status(403).json({ error: 'Change your password before continuing' });
    }
    if (user.tenantId) {
      return res.status(403).json({ error: 'This is a tenant account and cannot use the back office' });
    }

    // Resolved per request, not at boot: the two refusals above must read the
    // same whether or not the file is there, and a server started before the
    // copy landed should serve it the moment it appears.
    const path = candidates.find((p) => existsSync(p));
    if (!path) return res.status(404).json({ error: NOT_DEPLOYED });

    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.setHeader('Content-Length', String(statSync(path).size));
    res.setHeader('Content-Disposition', 'inline; filename="user-manual.html"');
    res.setHeader('Cache-Control', 'private, no-store');
    res.setHeader('X-Content-Type-Options', 'nosniff');
    const stream = createReadStream(path);
    stream.on('error', () => {
      if (!res.headersSent) res.status(404).json({ error: NOT_DEPLOYED });
    });
    stream.pipe(res);
  });

  return router;
}
