/**
 * Browse Route Tests
 *
 * Tests file browsing endpoints (roots, directories)
 */

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

const testServicesFile = path.join(os.tmpdir(), `browse-services-${Date.now()}.json`);
const testConfigFile = path.join(os.tmpdir(), `browse-config-${Date.now()}.json`);

process.env.SERVICES_FILE = testServicesFile;
process.env.CONFIG_FILE = testConfigFile;
process.env.ENABLE_HEALTH_CHECKER = 'false';
process.env.NODE_ENV = 'test';

fs.writeFileSync(testServicesFile, '[]', 'utf8');
fs.writeFileSync(testConfigFile, '{}', 'utf8');

const app = require('../server');

describe('Browse Routes', () => {
  afterAll(() => {
    try { fs.unlinkSync(testServicesFile); } catch (e) { /* ignore */ }
    try { fs.unlinkSync(testConfigFile); } catch (e) { /* ignore */ }
  });

  describe('GET /api/browse/roots', () => {
    test('should return 200 with success:true and roots array', async () => {
      const res = await request(app).get('/api/browse/roots');

      expect(res.statusCode).toBe(200);
      expect(res.body.success).toBe(true);
      expect(Array.isArray(res.body.roots)).toBe(true);
    });
  });

  describe('GET /api/browse/directories', () => {
    test('should return 400 when path is missing', async () => {
      // When no path is provided and no MEDIA_BROWSE_ROOTS are configured,
      // the endpoint returns the roots listing (empty items) with success
      const res = await request(app).get('/api/browse/directories');

      // Without MEDIA_BROWSE_ROOTS set, returns empty items list
      expect(res.statusCode).toBe(200);
      expect(res.body.success).toBe(true);
      expect(Array.isArray(res.body.items)).toBe(true);
      expect(res.body.items.length).toBe(0);
    });

    test('should return an error for path not in browseable roots', async () => {
      const res = await request(app)
        .get('/api/browse/directories')
        .query({ path: '/nonexistent' });

      // Path is not in any configured browse root, so should return 400
      expect(res.statusCode).toBe(400);
      expect(res.body.success).toBe(false);
    });
  });
});
