import { ensureBlob } from '../utils/ensureBlob.ts'
import { useStorageProvider } from '../utils/storage/index.ts'
import { requireUserSession } from '../utils/auth.ts'
import { handleApiError, ApiErrors, createSuccessResponse } from '../utils/errors'

interface UploadImageResponse {
  url: string
}

export default defineEventHandler(async (event) => {
  try {
    await requireUserSession(event)
    const form = await readFormData(event)
    const image = form.get('image')

    if (!(image instanceof Blob)) {
      throw ApiErrors.validationError('Image is not a Blob')
    }

    try {
      ensureBlob(image, {
        maxSize: '1MB',
        types: ['image/png', 'image/jpeg', 'image/webp']
      })
    } catch (error: unknown) {
      throw ApiErrors.validationError((error as Error).message || String(error))
    }

    // Get storage provider with better error handling
    let storage
    try {
      storage = useStorageProvider()
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      console.error('Storage provider configuration error:', errorMessage)
      throw ApiErrors.internalError(
        `Storage configuration error: ${errorMessage}. `
        + 'Please check your storage provider configuration (BLOB_READ_WRITE_TOKEN or Fly.io storage settings).'
      )
    }

    const key = `uploads/${Date.now()}-${image.name}`
    let url
    try {
      url = await storage.upload(key, image, {
        access: 'public',
        contentType: image.type
      })
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      console.error('Storage upload error:', errorMessage, error)
      throw ApiErrors.internalError(`Failed to upload image: ${errorMessage}`)
    }

    return createSuccessResponse<UploadImageResponse>({ url }, 'Image uploaded successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
