import { Hono } from 'hono'; import { cors } from 'hono/cors'; import type { Database } from './database.js'; import type { Firehose } from './firehose.js'; import type { Engine } from './engine.js'; import type { BotPlayer } from './bot-player.js'; import type { Poster } from './poster.js'; import type { Logger } from './logger.js'; import type { AppConfig } from './types.js'; export class Api { readonly app: Hono; private db: Database; private log: Logger; private startedAt: Date; private firehose: Firehose | null = null; private engine: Engine | null = null; private botPlayer: BotPlayer | null = null; private poster: Poster | null = null; constructor(db: Database, logger: Logger, _config: AppConfig['api']) { this.db = db; this.log = logger.child({ component: 'api' }); this.startedAt = new Date(); this.app = new Hono(); this.setupMiddleware(); this.setupRoutes(); } setSubsystems(opts: { firehose?: Firehose; engine?: Engine; botPlayer?: BotPlayer; poster?: Poster }): void { if (opts.firehose) this.firehose = opts.firehose; if (opts.engine) this.engine = opts.engine; if (opts.botPlayer) this.botPlayer = opts.botPlayer; if (opts.poster) this.poster = opts.poster; } private setupMiddleware(): void { this.app.use('*', cors({ origin: ['https://checkmate.blue', 'http://localhost:5173', 'http://127.0.0.1:5173'], })); } private setupRoutes(): void { this.app.get('/health', async (c) => { const dbHealthy = await this.db.isHealthy(); const uptimeMs = Date.now() - this.startedAt.getTime(); return c.json({ ok: dbHealthy && (this.firehose?.status().connected ?? false), uptime: uptimeMs, database: dbHealthy ? 'connected' : 'disconnected', firehose: this.firehose?.status() ?? null, engine: this.engine ? { activeWorkers: this.engine.getActiveCount() } : null, botPlayer: this.botPlayer?.status() ?? null, poster: this.poster?.status() ?? null, }); }); this.app.get('/games/active', async (c) => { const limit = Math.min(parseInt(c.req.query('limit') ?? '50', 10), 100); const games = await this.db.getActiveGames(limit); return c.json(games); }); this.app.get('/games/recent', async (c) => { const limit = Math.min(parseInt(c.req.query('limit') ?? '50', 10), 100); const offset = parseInt(c.req.query('offset') ?? '0', 10); const games = await this.db.getRecentGames(limit, offset); return c.json(games); }); this.app.get('/games/player/:did', async (c) => { const did = c.req.param('did'); const limit = Math.min(parseInt(c.req.query('limit') ?? '50', 10), 100); const games = await this.db.getGamesForPlayer(did, limit); return c.json(games); }); this.app.get('/players/:did/stats', async (c) => { const did = c.req.param('did'); const stats = await this.db.getPlayerStats(did); return c.json({ did, ...stats }); }); this.app.get('/challenges/open', async (c) => { const challenges = await this.db.getOpenChallenges(); return c.json(challenges); }); } }