import { describe, expect, it } from 'vitest'
import { assertImageFile, assertImageFiles } from '../../http/upload'
import { assertStorageConfiguration } from '../../lib/storage'

const imageFixtures: Record<string, { name: string; buffer: Buffer }> = {
  'image/jpeg': { name: 'upload.jpg', buffer: Buffer.from([0xff, 0xd8, 0xff, 0x00]) },
  'image/png':  { name: 'upload.png', buffer: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) },
}

function fakeFile(mimetype: string, originalname?: string): Express.Multer.File {
  const fixture = imageFixtures[mimetype]

  return {
    fieldname: 'file',
    originalname: originalname ?? fixture?.name ?? 'upload.bin',
    encoding: '7bit',
    mimetype,
    size: fixture?.buffer.length ?? 10,
    buffer: fixture?.buffer ?? Buffer.from('x'),
    stream: undefined as any,
    destination: '',
    filename: '',
    path: '',
  }
}

describe('infrastructure boundaries', () => {
  it('keeps upload validation strict before service-layer storage writes happen', () => {
    expect(() => assertImageFile(fakeFile('image/jpeg'))).not.toThrow()
    expect(() => assertImageFiles([fakeFile('image/png')])).not.toThrow()
    expect(() => assertImageFile(fakeFile('application/pdf', 'id.pdf'))).toThrow('Unsupported or spoofed image file')
    expect(() => assertImageFiles([fakeFile('image/png'), fakeFile('text/plain', 'notes.txt')])).toThrow('notes.txt')
  })

  it('requires an explicit file storage mount in production', () => {
    const previousNodeEnv = process.env.NODE_ENV
    const previousRoot = process.env.FILE_STORAGE_ROOT
    process.env.NODE_ENV = 'production'
    delete process.env.FILE_STORAGE_ROOT

    expect(() => assertStorageConfiguration()).toThrow('FILE_STORAGE_ROOT must be set in production')

    process.env.NODE_ENV = previousNodeEnv
    process.env.FILE_STORAGE_ROOT = previousRoot
  })
})
