import { describe, it, expect } from 'vitest';
import express from 'express';
import request from 'supertest';
import { mountMetaApi } from './meta-api.js';

function makeApp(repos: string[], configured?: string[]) {
  const app = express();
  mountMetaApi(app, { repo: { getDistinctRepos: () => repos }, configuredRepos: configured });
  return app;
}

describe('meta-api', () => {
  it('GET /api/repos merges configured + job repos, deduped and sorted', async () => {
    const res = await request(makeApp(['b', 'a', 'b'], ['c', 'a', ''])).get('/api/repos');
    expect(res.status).toBe(200);
    expect(res.body.repos).toEqual(['a', 'b', 'c']);
  });

  it('GET /api/repos returns 500 when the repo throws', async () => {
    const app = express();
    mountMetaApi(app, { repo: { getDistinctRepos: () => { throw new Error('db down'); } } });
    const res = await request(app).get('/api/repos');
    expect(res.status).toBe(500);
    expect(res.body.error).toBe('Failed to fetch repos');
  });

  it('GET /api/version returns a non-empty version string', async () => {
    const res = await request(makeApp([])).get('/api/version');
    expect(res.status).toBe(200);
    expect(typeof res.body.version).toBe('string');
    expect(res.body.version.length).toBeGreaterThan(0);
  });
});
