import type { RuntimeConfig } from 'nuxt/schema'
import type { StorageProvider, StorageProviderType } from './types'
import { VercelBlobStorage } from './vercel-blob'
import { FlyIoStorage } from './fly-io'

/**
 * Get the configured storage provider based on runtime config
 *
 * Priority:
 * 1. Custom storage provider (if storageProvider is 'custom' and customStorageProvider is set)
 * 2. Fly.io storage (if storageProvider is 'fly-io' and Fly.io config is present)
 * 3. Vercel Blob (default, if blobReadWriteToken is present)
 *
 * @param config - Runtime config from Nuxt
 * @param customProvider - Optional custom storage provider from extending app
 * @returns The configured storage provider instance
 */
export function getStorageProvider(
  config: RuntimeConfig,
  customProvider?: StorageProvider
): StorageProvider {
  const storageProvider = (config.storageProvider as StorageProviderType) || 'vercel-blob'

  // If custom provider is explicitly set and provided, use it
  if (storageProvider === 'custom' && customProvider) {
    return customProvider
  }

  // If Fly.io storage is configured, use it
  if (storageProvider === 'fly-io') {
    const flyConfig = {
      accessKeyId: config.flyStorageAccessKeyId as string,
      secretAccessKey: config.flyStorageSecretAccessKey as string,
      endpoint: config.flyStorageEndpoint as string,
      region: (config.flyStorageRegion as string) || 'auto',
      bucketName: config.flyStorageBucketName as string,
      publicUrlBase: config.flyStoragePublicUrlBase as string | undefined
    }

    if (flyConfig.accessKeyId && flyConfig.secretAccessKey && flyConfig.endpoint && flyConfig.bucketName) {
      return new FlyIoStorage(flyConfig)
    }

    throw new Error(
      'Fly.io storage is configured but required environment variables are missing. '
      + 'Required: FLY_STORAGE_ACCESS_KEY_ID, FLY_STORAGE_SECRET_ACCESS_KEY, '
      + 'FLY_STORAGE_ENDPOINT, FLY_STORAGE_BUCKET_NAME'
    )
  }

  // Default to Vercel Blob if token is present
  const blobToken = config.blobReadWriteToken as string
  if (blobToken) {
    return new VercelBlobStorage(blobToken)
  }

  throw new Error(
    'No storage provider configured. '
    + 'Set BLOB_READ_WRITE_TOKEN for Vercel Blob, or configure Fly.io storage with '
    + 'STORAGE_PROVIDER=fly-io and Fly.io environment variables.'
  )
}

/**
 * Get storage provider instance using current runtime config
 * This is a convenience function for use in API routes
 */
export function useStorageProvider(customProvider?: StorageProvider): StorageProvider {
  const config = useRuntimeConfig()
  return getStorageProvider(config, customProvider)
}
