import { Router } from 'express';
import { randomUUID } from 'crypto';
import { getAllPublicServers } from '../cqrs';
import { getReleaseManifestUrl, getServerTag } from '../config/variables';
import { SERVER_BUILD_VERSION } from '../generated/build-version';
import { connectedUsers } from '../websocket/state';

const router = Router();
const SERVER_INSTANCE_ID = typeof process.env.METOYOU_SERVER_INSTANCE_ID === 'string'
  && process.env.METOYOU_SERVER_INSTANCE_ID.trim().length > 0
  ? process.env.METOYOU_SERVER_INSTANCE_ID.trim()
  : randomUUID();

function getServerProjectVersion(): string {
  return typeof process.env.METOYOU_SERVER_VERSION === 'string' && process.env.METOYOU_SERVER_VERSION.trim().length > 0
    ? process.env.METOYOU_SERVER_VERSION.trim()
    : SERVER_BUILD_VERSION;
}

router.get('/health', async (_req, res) => {
  const servers = await getAllPublicServers();

  res.json({
    status: 'ok',
    timestamp: Date.now(),
    serverCount: servers.length,
    connectedUsers: connectedUsers.size,
    serverInstanceId: SERVER_INSTANCE_ID,
    serverVersion: getServerProjectVersion(),
    releaseManifestUrl: getReleaseManifestUrl(),
    serverTag: getServerTag()
  });
});

router.get('/time', (_req, res) => {
  res.json({ now: Date.now() });
});

export default router;
