import { readFileSync } from 'fs';
import { join } from 'path';
import { Router, Request, Response } from 'express';
import { prismaUnscoped } from '../lib/prisma';

export const healthRouter = Router();

/**
 * The commit this process runs, from the REVISION file a release carries
 * (docs/deploy/reliable-deploys.md). The deploy checks it after a switch, so
 * it can't mistake some other process for the new release. Short, as in the
 * release name; absent when run from a checkout.
 */
const revision = (() => {
  try {
    return readFileSync(join(process.cwd(), 'REVISION'), 'utf8').trim().slice(0, 7) || undefined;
  } catch {
    return undefined;
  }
})();

/** Liveness — process is up. */
healthRouter.get('/', (_req: Request, res: Response) => {
  res.json({ status: 'ok', service: 'hostelcare-backend', ...(revision ? { revision } : {}) });
});

/** Readiness — database is reachable. */
healthRouter.get('/db', async (_req: Request, res: Response) => {
  try {
    await prismaUnscoped.$queryRaw`SELECT 1`;
    res.json({ status: 'ok', db: 'reachable' });
  } catch {
    res.status(503).json({ status: 'error', db: 'unreachable' });
  }
});
