import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { Mock } from 'vitest';
import { Readable } from 'stream';

vi.mock('../../src/services/fsScanner', () => ({ scanDirectory: vi.fn() }));
vi.mock('../../src/services/archiveReader', () => ({ streamArchiveEntry: vi.fn() }));
vi.mock('../../src/plugins/prisma', () => ({
  default: {
    game: { findUnique: vi.fn(), create: vi.fn() },
    romFile: { upsert: vi.fn() },
  },
}));

import importDirectory, { createSlug } from '../../src/services/importService';
import { scanDirectory } from '../../src/services/fsScanner';
import { streamArchiveEntry } from '../../src/services/archiveReader';
import prisma from '../../src/plugins/prisma';
import { createHash } from 'crypto';

beforeEach(() => {
  vi.restoreAllMocks();
});

describe('services/importService (archive entries)', () => {
  it('procesa una entrada interna usando streamArchiveEntry y hace upsert', async () => {
    const files = [
      {
        path: '/roms/collection.zip::inner/rom1.bin',
        containerPath: '/roms/collection.zip',
        entryPath: 'inner/rom1.bin',
        filename: 'rom1.bin',
        name: 'inner/rom1.bin',
        size: 123,
        format: 'bin',
        isArchiveEntry: true,
      },
    ];

    const data = Buffer.from('import-archive-test');

    (scanDirectory as unknown as Mock).mockResolvedValue(files);
    (streamArchiveEntry as unknown as Mock).mockResolvedValue(Readable.from([data]));

    (prisma.game.findUnique as unknown as Mock).mockResolvedValue(null);
    (prisma.game.create as unknown as Mock).mockResolvedValue({
      id: 77,
      title: 'ROM1',
      slug: 'rom1',
    });
    (prisma.romFile.upsert as unknown as Mock).mockResolvedValue({ id: 1 });

    const md5 = createHash('md5').update(data).digest('hex');

    const summary = await importDirectory({ dir: '/roms', persist: true });

    expect((streamArchiveEntry as unknown as Mock).mock.calls.length).toBe(1);
    expect((streamArchiveEntry as unknown as Mock).mock.calls[0][0]).toBe('/roms/collection.zip');
    expect((streamArchiveEntry as unknown as Mock).mock.calls[0][1]).toBe('inner/rom1.bin');

    expect((prisma.romFile.upsert as unknown as Mock).mock.calls.length).toBe(1);
    const upsertArgs = (prisma.romFile.upsert as unknown as Mock).mock.calls[0][0];
    expect(upsertArgs.where).toEqual({ checksum: md5 });
    expect(upsertArgs.create.filename).toBe('rom1.bin');
    expect(upsertArgs.create.path).toBe('/roms/collection.zip::inner/rom1.bin');

    expect(summary).toEqual({ processed: 1, createdCount: 1, upserted: 1 });
  });
});
