import { fetchPublicJson } from '@/utils/publicExplorer'
import { getExplorerApiBase } from './blockscout'

const WALLETCONNECT_CONFIG_PATH = '/explorer-api/v1/walletconnect/config'

export interface WalletConnectConfigResponse {
  status: 'stub' | 'disabled' | string
  enabled: boolean
  projectId: string
  relayUrl: string
  metadataUrl: string
  requiredNamespaces: string[]
  supportedChains: number[]
  fallbackAuth: string
  message: string
  updatedAt: string
}

export async function getWalletConnectConfig(): Promise<WalletConnectConfigResponse | null> {
  try {
    return await fetchPublicJson<WalletConnectConfigResponse>(WALLETCONNECT_CONFIG_PATH)
  } catch {
    return null
  }
}

export async function registerWalletConnectSession(input: {
  sessionId: string
  address: string
  chainId?: number
}): Promise<void> {
  const response = await fetch(`${getExplorerApiBase()}/explorer-api/v1/walletconnect/session`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      sessionId: input.sessionId,
      address: input.address,
      chainId: input.chainId,
    }),
  })
  if (!response.ok) {
    const text = await response.text().catch(() => '')
    throw new Error(text || `WalletConnect session register failed (${response.status})`)
  }
}
