import { logger as rootLogger } from '../config/logger'
import type { StorageProviderInterface, StorageUploadPayload } from './types'

export type StorageHealthReason =
  | 'ok'
  | 'not_configured'
  | 'needs_restart'
  | 'auth_error'
  | 'billing_error'
  | 'bucket_not_found'
  | 'network_error'
  | 'unknown'

export interface StorageHealthStatus {
  healthy: boolean
  configured: boolean
  reason: StorageHealthReason
  message: string
}

/**
 * Singleton registry para o storage provider ativo.
 * O plugin UnifiedStorageProvider se registra aqui durante o activate().
 * O plugin uploads chama uploadFile() para enviar ao storage registrado.
 */
class StorageProviderRegistry {
  private provider: StorageProviderInterface | null = null
  private healthy = false
  private lastHealthStatus: StorageHealthStatus = {
    healthy: false,
    configured: false,
    reason: 'not_configured',
    message: 'Storage não inicializado.',
  }

  register(provider: StorageProviderInterface): void {
    this.provider = provider
    this.lastHealthStatus = { healthy: true, configured: true, reason: 'ok', message: 'Wasabi inicializado.' }
    rootLogger.info('[StorageProvider] Provider registrado')
  }

  isRegistered(): boolean {
    return this.provider !== null
  }

  isHealthy(): boolean {
    return this.healthy
  }

  getLastHealthStatus(): StorageHealthStatus {
    return this.lastHealthStatus
  }

  setHealthStatus(status: StorageHealthStatus): void {
    this.lastHealthStatus = status
    this.healthy = status.healthy
  }

  async uploadFile(payload: StorageUploadPayload): Promise<{ provider: string; path: string }> {
    if (!this.provider) {
      throw new Error('Nenhum storage provider registrado. Ative o plugin UnifiedStorageProvider.')
    }
    return this.provider.upload(payload)
  }

  /** Atualiza o status de saúde — chamado periodicamente pelo UnifiedStorageProvider */
  async updateHealth(): Promise<void> {
    if (!this.provider) {
      this.healthy = false
      this.lastHealthStatus = {
        healthy: false,
        configured: false,
        reason: 'not_configured',
        message: 'Storage não configurado. Acesse Admin > Plugins > UnifiedStorageProvider.',
      }
      return
    }
    try {
      const status = await this.provider.checkDetailedHealth()
      this.healthy = status.healthy
      this.lastHealthStatus = status
    } catch {
      this.healthy = false
      this.lastHealthStatus = {
        healthy: false,
        configured: true,
        reason: 'unknown',
        message: 'Erro desconhecido ao verificar o storage.',
      }
    }
  }

  async getBuffer(path: string): Promise<Buffer | null> {
    if (!this.provider) return null
    return this.provider.getBuffer(path)
  }

  async deletePrefix(prefix: string): Promise<{ deleted: number }> {
    if (!this.provider) {
      rootLogger.warn('[StorageProvider] deletePrefix chamado mas nenhum provider está registrado')
      return { deleted: 0 }
    }
    return this.provider.deletePrefix(prefix)
  }

  unregister(): void {
    this.provider = null
    this.healthy = false
    rootLogger.info('[StorageProvider] Provider removido')
  }
}

export const storageProvider = new StorageProviderRegistry()
export type { StorageUploadPayload, StorageProviderInterface }
