import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

// Movement Testnet Configuration
export const MOVEMENT_TESTNET_CONFIG = {
  name: 'Movement Testnet',
  fullnode: 'https://testnet.bardock.movementnetwork.xyz/v1',
  faucet: 'https://faucet.testnet.bardock.movementnetwork.xyz/',
} as const;

export class MovementAptosClient {
  private aptos: Aptos;
  private config = MOVEMENT_TESTNET_CONFIG;

  constructor() {
    const aptosConfig = new AptosConfig({
      network: Network.CUSTOM,
      fullnode: this.config.fullnode,
      faucet: this.config.faucet,
    });
    this.aptos = new Aptos(aptosConfig);
  }


  // Get network configuration
  getNetworkConfig() {
    return this.config;
  }

  // Get account info
  async getAccountInfo(address: string) {
    return this.aptos.getAccountInfo({ accountAddress: address });
  }

  // Get MOVE balance (Movement Network's native token)
  async getAccountBalance(address: string, coinType?: string) {
    // Movement Network typically uses Move coin or APT depending on configuration
    const moveTokenType = coinType || "0x1::aptos_coin::AptosCoin"; // Default to APT for Movement compatibility
    
    try {
      const resource = await this.aptos.getAccountResource({
        accountAddress: address,
        resourceType: `0x1::coin::CoinStore<${moveTokenType}>`,
      });
      return (resource as any).coin.value;
    } catch (error: any) {
      console.error('Error fetching balance:', error);
      if (error.message?.includes('resource_not_found')) {
        return '0'; // Account not registered for this coin type
      }
      throw error;
    }
  }

  // Get account resources to see all available coins
  async getAccountResources(address: string) {
    return this.aptos.getAccountResources({ accountAddress: address });
  }

  // Get transaction by hash
  async getTransaction(txnHash: string) {
    return this.aptos.getTransactionByHash({ transactionHash: txnHash });
  }

  // Build transaction payload (excluding private key - wallet handles signing)
  buildTransactionPayload(payload: {
    function: string
    typeArguments?: string[]
    functionArguments?: any[]
  }) {
    return {
      payload: {
        type: "entry_function_payload" as const,
        function: payload.function as `${string}::${string}::${string}`,
        type_arguments: payload.typeArguments || [],
        arguments: payload.functionArguments || []
      }
    };
  }
}

// Default client instance
export const movementAptosClient = new MovementAptosClient();
