import fs from 'node:fs'
import path from 'node:path'
import { describe, it, expect, afterEach } from 'vitest'
import { persistMultipartImages } from '../upload-images.js'

const UPLOADS_DIR = path.join(process.cwd(), 'uploads')
const TEST_PREFIX = 'upload-test-'

describe('persistMultipartImages with eager=false', () => {
  afterEach(async () => {
    const files = await fs.promises.readdir(UPLOADS_DIR).catch(() => [])
    for (const file of files) {
      if (file.startsWith(TEST_PREFIX)) {
        await fs.promises.unlink(path.join(UPLOADS_DIR, file)).catch(() => {})
      }
    }
  })

  it('returns original format URLs when eager=false', async () => {
    const sharp = (await import('sharp')).default
    const testImagePath = path.join(UPLOADS_DIR, `${TEST_PREFIX}original2.png`)
    await sharp({ create: { width: 100, height: 100, channels: 3, background: { r: 0, g: 255, b: 0 } } })
      .png()
      .toFile(testImagePath)

    const mockRequest = {
      isMultipart: () => true,
      parts: async function* () {
        const buffer = await fs.promises.readFile(testImagePath)
        yield {
          file: true,
          filename: 'test.png',
          toBuffer: async () => buffer,
        }
      },
    }

    const urls = await persistMultipartImages(mockRequest, {
      maxFiles: 1,
      maxFileBytes: 20 * 1024 * 1024,
      subdir: '',
      eager: false,
    })

    expect(urls).toHaveLength(1)
    expect(urls[0]).toMatch(/\/uploads\/[a-f0-9-]+\.png$/)
  })
})
