import express, { Request, Response } from 'express';
import { Repository } from '../db/repository.js';
import { requireAuth } from './auth.js';

/**
 * Job detail API (`GET /api/jobs/:jobId`), extracted verbatim from
 * createCoreServer (bridge/server.ts). Registration order is preserved by
 * the mount call site in server.ts.
 */
export function mountJobsApi(
  app: express.Application,
  deps: { repo: Repository; authActive: boolean },
): void {
  const { repo, authActive } = deps;

  // --- Job detail API ---
  // Gate on viewer: getJob returns null for jobs the caller cannot see (Task 10 + 16).
  // When auth is inactive, req.user is undefined → repository falls back to 1=1 (no filter).
  const jobDetailHandlers: express.RequestHandler[] = [];
  if (authActive) jobDetailHandlers.push(requireAuth);
  jobDetailHandlers.push(async (req: Request, res: Response) => {
    try {
      const viewer = (req.user as Express.User | undefined) ?? undefined;
      const job = await repo.getJob(req.params.jobId, viewer ? { viewer } : undefined);
      if (!job) {
        res.status(404).json({ error: 'Job not found' });
        return;
      }
      res.json(job);
    } catch {
      res.status(500).json({ error: 'Failed to fetch job' });
    }
  });
  app.get('/api/jobs/:jobId', ...jobDetailHandlers);
}
