'use strict';

const fs = require('fs');
const path = require('path');
const express = require('express');
const request = require('supertest');

// This test mounts the EXACT version route module that production wires into
// apiRouter via require('../routes/version') in src/app.js. There is no
// duplicated handler — both production and this test resolve the same module.

describe('HTTP /api/v1/version route contract (real production module)', () => {
  let app;
  let versionModule;

  beforeAll(() => {
    app = express();
    versionModule = require('../../routes/version');
    app.use('/api/v1', versionModule.buildRouter());
  });

  it('returns package semver via the real version route module', async () => {
    const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8'));
    const res = await request(app).get('/api/v1/version');
    expect(res.status).toBe(200);
    expect(res.body.success).toBe(true);
    expect(res.body.version).toBe(pkg.version);
    expect(res.body.version).toMatch(/^\d+\.\d+\.\d+$/);
    expect(res.body.name).toBe('dashcaddy-api');
    expect(res.body.node).toMatch(/^v\d+/);
    expect(res.body.platform).toBe(process.platform);
    expect(res.body.arch).toBe(process.arch);
    expect(typeof res.body.uptime).toBe('number');
  });

  it('version module exports getVersion/getName/buildRouter', () => {
    expect(typeof versionModule.getVersion).toBe('function');
    expect(typeof versionModule.getName).toBe('function');
    expect(typeof versionModule.buildRouter).toBe('function');
    expect(versionModule.getVersion()).toMatch(/^\d+\.\d+\.\d+$/);
  });

  it('src/app.js wires routes/version.js into the apiRouter', () => {
    const appSource = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'app.js'), 'utf8');
    expect(appSource).toMatch(/require\(['"]\.\.\/routes\/version['"]\)/);
    expect(appSource).toMatch(/versionRoute\.buildRouter\(\)/);
  });
});
