import { getChain } from '@/config';

type EndpointType = 'graphql' | 'rpc' | 'txnBot';

class ChainConfigService {
  getEndpoint(chainId: number, type: EndpointType): string {
    const chain = getChain(chainId);
    if (!chain) {
      throw new Error(`Chain ${chainId} is not configured.`);
    }

    switch (type) {
      case 'graphql':
        return this.ensureEndpoint(chain.graphql, chainId, 'GraphQL');
      case 'rpc':
        return this.ensureEndpoint(chain.cheats?.rpc, chainId, 'RPC');
      case 'txnBot':
        return this.ensureEndpoint(chain.cheats?.txnBot, chainId, 'txnBot');
      default:
        // Exhaustiveness check
        assertNever(type);
    }
  }

  private ensureEndpoint(value: string | null | undefined, chainId: number, label: string): string {
    const normalized = value?.trim();
    if (!normalized) {
      throw new Error(`${label} endpoint not configured for chain ${chainId}.`);
    }
    if (normalized.startsWith('http://') || normalized.startsWith('https://')) {
      return normalized;
    }
    return normalized.startsWith('/') ? normalized : `/${normalized}`;
  }
}

function assertNever(_x: never): never {
  throw new Error('Unsupported endpoint type');
}

export const chainConfigService = new ChainConfigService();
