import { FastifyInstance } from 'fastify';
import { readFileSync } from 'fs';
import { join } from 'path';

interface PackageJson {
  version: string;
}

let cachedVersion: string | null = null;

function getVersion(): string {
  if (cachedVersion) {
    return cachedVersion;
  }

  try {
    const packageJsonPath = join(process.cwd(), 'package.json');
    const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson;
    cachedVersion = packageJson.version;
    return cachedVersion;
  } catch {
    return 'unknown';
  }
}

export default async function (fastify: FastifyInstance) {
  fastify.get('/', async function () {
    return { version: getVersion() };
  });
}
