import express, { Request, Response } from 'express';

/**
 * meta-api.ts — small, dependency-light "meta/info" endpoints extracted from
 * createCoreServer (server.ts) to keep that bootstrap function focused on
 * wiring. These are unique, order-independent read endpoints:
 *   GET /api/version — build/version string
 *   GET /api/repos   — distinct repos from jobs ∪ configured repos
 *
 * Auth note: the `requireAuth` guard for /api/repos is registered separately
 * in server.ts's auth block (`app.use('/api/repos', requireAuth)`); /api/version
 * is intentionally unauthenticated. Mounting position is preserved at the call
 * site so that ordering relative to that guard is unchanged.
 */

export interface MetaApiDeps {
  /** Repository (only getDistinctRepos is used). */
  repo: { getDistinctRepos(): string[] };
  /** Repos declared in config.yaml, merged with the ones seen in jobs. */
  configuredRepos?: string[];
}

export function mountMetaApi(app: express.Application, deps: MetaApiDeps): void {
  const { repo, configuredRepos } = deps;

  // Version endpoint
  app.get('/api/version', async (_req: Request, res: Response) => {
    let version = 'dev';
    try {
      const mod = await import('../generated/version.js');
      version = mod.APP_VERSION;
    } catch {
      try {
        const { execSync } = await import('child_process');
        version = execSync("TZ=UTC git log -1 --format=%cd --date=format:'%Y%m%d.%H%M%S'", { encoding: 'utf-8' }).trim();
      } catch {
        // keep 'dev'
      }
    }
    res.json({ version });
  });

  app.get('/api/repos', (_req: Request, res: Response) => {
    try {
      const reposFromJobs = repo.getDistinctRepos();
      const reposFromConfig = (configuredRepos ?? []).filter(Boolean);
      const repos = Array.from(new Set([...reposFromConfig, ...reposFromJobs])).sort();
      res.json({ repos });
    } catch {
      res.status(500).json({ error: 'Failed to fetch repos' });
    }
  });
}
