/**
 * DC-077 i18n route + DC-071 error tracker route tests
 */
const express = require('express');
const request = require('supertest');

function createI18nApp() {
  const app = express();
  app.use(express.json());
  const routes = require('../../routes/i18n');
  const wrap = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
  app.use('/api/v1', routes());
  return app;
}

describe('DC-077: i18n Routes', () => {
  it('GET /i18n/languages returns 31 languages', async () => {
    const app = createI18nApp();
    const res = await request(app).get('/api/v1/i18n/languages');

    expect(res.status).toBe(200);
    expect(res.body.success).toBe(true);
    expect(res.body.languages).toHaveLength(31);
    expect(res.body.default).toBe('en');
  });

  it('GET /i18n/languages marks Arabic, Persian, and Urdu as RTL', async () => {
    const app = createI18nApp();
    const res = await request(app).get('/api/v1/i18n/languages');

    const rtl = (code) => {
      const entry = res.body.languages.find(l => l.code === code);
      expect(entry).toBeTruthy();
      expect(entry.name).not.toBe(code);
      return entry.rtl;
    };
    expect(rtl('ar')).toBe(true);
    expect(rtl('fa')).toBe(true);
    expect(rtl('ur')).toBe(true);
    const english = res.body.languages.find(l => l.code === 'en');
    expect(english.rtl).toBe(false);
  });

  it('GET /i18n/translations/fa returns Persian strings, not raw English', async () => {
    const app = createI18nApp();
    const res = await request(app).get('/api/v1/i18n/translations/fa');
    expect(res.status).toBe(200);
    expect(res.body.translations['action.open']).not.toBe('Open');
    expect(res.body.translations['filter.online']).not.toBe('Online');
  });

  it('GET /i18n/translations/en returns English translations', async () => {
    const app = createI18nApp();
    const res = await request(app).get('/api/v1/i18n/translations/en');

    expect(res.status).toBe(200);
    expect(res.body.lang).toBe('en');
    expect(res.body.translations['dashboard.title']).toBe('Dashboard');
  });

  it('GET /i18n/translations/es returns Spanish translations', async () => {
    const app = createI18nApp();
    const res = await request(app).get('/api/v1/i18n/translations/es');

    expect(res.status).toBe(200);
    expect(res.body.lang).toBe('es');
    expect(res.body.translations['dashboard.title']).toBe('Panel de control');
  });

  it('GET /i18n/translations/xx returns 400 for unsupported', async () => {
    const app = createI18nApp();
    const res = await request(app).get('/api/v1/i18n/translations/xx');

    expect(res.status).toBe(400);
    expect(res.body.success).toBe(false);
    expect(res.body.supported).toContain('en');
  });
});
