import * as official from './official'
import * as infinite from './infinite'

// Engine padrão global: lida de BAILEYS_ENGINE (fallback para 'infinite')
const defaultEngineType = process.env.BAILEYS_ENGINE ?? 'infinite'

function resolveEngine(type: string) {
  return type === 'infinite' ? infinite : official
}

/**
 * Retorna os exports da engine selecionada para uma instância específica.
 * Permite que cada instância use uma engine diferente (infinite ou official).
 * Se não informado, usa BAILEYS_ENGINE do ambiente (padrão: 'infinite').
 */
export function getEngine(engineType?: string | null): {
  makeWASocket: any
  useMultiFileAuthState: any
  fetchLatestBaileysVersion: any
  makeCacheableSignalKeyStore: any
  downloadMediaMessage: any
  getContentType: any
  generateMessageIDV2: any
  generateWAMessageFromContent: any
  isJidGroup: any
  isJidStatusBroadcast: any
} {
  const e = resolveEngine(engineType ?? defaultEngineType)
  return {
    makeWASocket:               e.makeWASocket as any,
    useMultiFileAuthState:      e.useMultiFileAuthState as any,
    fetchLatestBaileysVersion:  e.fetchLatestBaileysVersion as any,
    makeCacheableSignalKeyStore: e.makeCacheableSignalKeyStore as any,
    downloadMediaMessage:       e.downloadMediaMessage as any,
    getContentType:             e.getContentType as any,
    generateMessageIDV2:        e.generateMessageIDV2 as any,
    generateWAMessageFromContent: e.generateWAMessageFromContent as any,
    isJidGroup:                 e.isJidGroup as any,
    isJidStatusBroadcast:       e.isJidStatusBroadcast as any,
  }
}

// Exports estáticos: usam a engine global (retrocompatibilidade com código existente)
const selectedEngine = resolveEngine(defaultEngineType)

export const makeWASocket = selectedEngine.makeWASocket as any
export const useMultiFileAuthState = selectedEngine.useMultiFileAuthState as any
export const DisconnectReason = selectedEngine.DisconnectReason as any
export const fetchLatestBaileysVersion = selectedEngine.fetchLatestBaileysVersion as any
export const makeCacheableSignalKeyStore = selectedEngine.makeCacheableSignalKeyStore as any
export const downloadMediaMessage = selectedEngine.downloadMediaMessage as any
export const getContentType = selectedEngine.getContentType as any
export const generateMessageIDV2 = selectedEngine.generateMessageIDV2 as any
export const generateWAMessageFromContent = selectedEngine.generateWAMessageFromContent as any
export const isJidGroup = selectedEngine.isJidGroup as any
export const isJidStatusBroadcast = selectedEngine.isJidStatusBroadcast as any
export { proto } from './official'

// Exportação estática de tipos para garantir segurança em tempo de compilação
export type { WASocket, ConnectionState, WAMessage, Contact, BinaryNode } from './official'
