import fs from 'node:fs'
import path from 'node:path'
import { describe, it, expect, beforeAll, afterAll } from 'vitest'

const UPLOADS_DIR = path.join(process.cwd(), 'uploads')

import { generateAllSizes, convertOriginalToWebp } from '../../../lib/image-resize.js'

describe('Admin gallery resize integration', () => {
  const testUuid = 'gallery-test-resize-uuid'
  const testOriginalPath = path.join(UPLOADS_DIR, `${testUuid}.png`)

  beforeAll(async () => {
    const sharp = (await import('sharp')).default
    await sharp({ create: { width: 200, height: 200, channels: 3, background: { r: 255, g: 0, b: 0 } } })
      .png()
      .toFile(testOriginalPath)
  })

  afterAll(async () => {
    await fs.promises.unlink(testOriginalPath).catch(() => {})
    const webpPath = path.join(UPLOADS_DIR, `${testUuid}.webp`)
    await fs.promises.unlink(webpPath).catch(() => {})
    const cacheDir = path.join(UPLOADS_DIR, '.cache')
    for (const width of [320, 640, 1024, 1600]) {
      for (const format of ['avif', 'webp']) {
        await fs.promises.unlink(path.join(cacheDir, `${testUuid}_w${width}.${format}`)).catch(() => {})
      }
    }
  })

  it('generateAllSizes + convertOriginalToWebp works on raw upload', async () => {
    await generateAllSizes(testUuid, '', testOriginalPath)
    const newUrl = await convertOriginalToWebp(testUuid, '')

    expect(newUrl).toBe(`/uploads/${testUuid}.webp`)

    // Verify original PNG is deleted
    const pngExists = await fs.promises
      .access(testOriginalPath)
      .then(() => true)
      .catch(() => false)
    expect(pngExists).toBe(false)

    // Verify cached files exist
    const cacheDir = path.join(UPLOADS_DIR, '.cache')
    for (const width of [320, 640, 1024, 1600]) {
      for (const format of ['avif', 'webp']) {
        const cachePath = path.join(cacheDir, `${testUuid}_w${width}.${format}`)
        const exists = await fs.promises
          .access(cachePath)
          .then(() => true)
          .catch(() => false)
        expect(exists).toBe(true)
      }
    }

    // Verify webp original exists
    const webpExists = await fs.promises
      .access(path.join(UPLOADS_DIR, `${testUuid}.webp`))
      .then(() => true)
      .catch(() => false)
    expect(webpExists).toBe(true)
  })
})
