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

// getNetworkIPs() senza argomenti dipende dalla piattaforma (fs, child_process,
// os.networkInterfaces): qui mockiamo quei moduli per esercitare in modo
// deterministico i rami WSL/non-WSL, altrimenti scoperti dagli altri test
// (che iniettano sempre `nets` per bypassare questo codice).
describe('server-utils.js — rilevamento piattaforma', () => {
    afterEach(() => {
        vi.restoreAllMocks()
        vi.resetModules()
        vi.doUnmock('fs')
        vi.doUnmock('child_process')
        vi.doUnmock('os')
    })

    it('senza WSL usa os.networkInterfaces()', async () => {
        vi.doMock('fs', () => ({
            existsSync: vi.fn(() => false),
            readFileSync: vi.fn(),
        }))
        vi.doMock('child_process', () => ({
            execSync: vi.fn(),
        }))
        vi.doMock('os', () => ({
            networkInterfaces: vi.fn(() => ({
                eth0: [{ family: 'IPv4', internal: false, address: '10.0.0.9' }],
            })),
        }))

        const { getNetworkIPs } = await import('../../src/server-utils.js')
        expect(getNetworkIPs()).toEqual(['10.0.0.9'])
    })

    it('su WSL interroga PowerShell e filtra gli IP LAN', async () => {
        vi.doMock('fs', () => ({
            existsSync: vi.fn(() => true),
            readFileSync: vi.fn(() => 'Microsoft WSL2'),
        }))
        vi.doMock('child_process', () => ({
            execSync: vi.fn(() => Buffer.from('192.168.1.42\n127.0.0.1\n172.17.0.1\n')),
        }))
        vi.doMock('os', () => ({
            networkInterfaces: vi.fn(),
        }))

        const { getNetworkIPs } = await import('../../src/server-utils.js')
        expect(getNetworkIPs()).toEqual(['192.168.1.42'])
    })

    it('su WSL se PowerShell fallisce restituisce array vuoto', async () => {
        vi.doMock('fs', () => ({
            existsSync: vi.fn(() => true),
            readFileSync: vi.fn(() => 'Microsoft WSL2'),
        }))
        vi.doMock('child_process', () => ({
            execSync: vi.fn(() => { throw new Error('powershell non disponibile') }),
        }))
        vi.doMock('os', () => ({
            networkInterfaces: vi.fn(),
        }))

        const { getNetworkIPs } = await import('../../src/server-utils.js')
        expect(getNetworkIPs()).toEqual([])
    })

    it('se la lettura di /proc/sys/kernel/osrelease lancia, tratta la piattaforma come non-WSL', async () => {
        vi.doMock('fs', () => ({
            existsSync: vi.fn(() => true),
            readFileSync: vi.fn(() => { throw new Error('permesso negato') }),
        }))
        vi.doMock('child_process', () => ({
            execSync: vi.fn(),
        }))
        vi.doMock('os', () => ({
            networkInterfaces: vi.fn(() => ({})),
        }))

        const { getNetworkIPs } = await import('../../src/server-utils.js')
        expect(getNetworkIPs()).toEqual([])
    })
})
