const fs = require('fs')
const path = require('path')
const os = require('os')
const { test } = require('node:test')
const assert = require('node:assert/strict')

test('uploadCommand exits when no valid files are provided', async () => {
  const screenshotPath = require.resolve('../lib/screenshot')
  require.cache[screenshotPath] = {
    id: screenshotPath,
    filename: screenshotPath,
    loaded: true,
    exports: {
      captureScreenshotFromCode: async () => Buffer.from(''),
      screenshotToDataUrl: () => 'data:image/png;base64,',
    },
  }

  delete require.cache[require.resolve('./upload')]
  const uploadCommand = require('./upload')

  const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bild-upload-empty-'))

  let exitCode
  const originalExit = process.exit
  process.exit = (code) => {
    exitCode = code
    throw new Error('process.exit')
  }

  try {
    await assert.rejects(
      () => uploadCommand([emptyDir], { appId: 'app-1' }),
      /process\.exit/,
    )
    assert.equal(exitCode, 1)
  } finally {
    process.exit = originalExit
    delete require.cache[require.resolve('./upload')]
    delete require.cache[screenshotPath]
  }
})
