import { describe, it, expect, vi } from 'vitest';

// Mockeamos el módulo `child_process` para controlar las llamadas a `exec`.
vi.mock('child_process', () => ({ exec: vi.fn() }));
import * as child_process from 'child_process';
import { listArchiveEntries } from '../../src/services/archiveReader';

describe('services/archiveReader', () => {
  it('lista entradas usando 7z -slt', async () => {
    const stdout = `Path = file1.txt\nSize = 123\nPacked Size = 0\n\nPath = dir/file2.bin\nSize = 456\nPacked Size = 0\n`;

    (child_process as any).exec.mockImplementation((cmd: any, cb: any) => {
      cb(null, stdout, '');
      return {} as any;
    });

    const entries = await listArchiveEntries('/roms/archive.7z', console);
    expect(entries.length).toBe(2);
    expect(entries[0].name).toBe('file1.txt');
    expect(entries[0].size).toBe(123);
    (child_process as any).exec.mockRestore?.();
  });

  it('usa unzip como fallback para zip cuando 7z falla', async () => {
    (child_process as any).exec
      .mockImplementationOnce((cmd: any, cb: any) => {
        // simular fallo de 7z
        cb(new Error('7z not found'), '', '');
        return {} as any;
      })
      .mockImplementationOnce((cmd: any, cb: any) => {
        // salida simulada de unzip -l
        cb(null, '   123 file1.txt\n   456 file2.bin\n', '');
        return {} as any;
      });

    const entries = await listArchiveEntries('/roms/archive.zip', console);
    expect(entries.length).toBe(2);
    expect(entries[0].name).toBe('file1.txt');
    (child_process as any).exec.mockRestore?.();
  });

  it('retorna vacío para formatos no soportados', async () => {
    const entries = await listArchiveEntries('/roms/simple.bin');
    expect(entries).toEqual([]);
  });
});
