/**
 * Safe SDK Helper Utilities - Utilities for Safe wallet operations
 */

import type { Address } from 'viem'

export interface SafeConfig {
  owners: Address[]
  threshold: number
  saltNonce?: string
}

export interface SafeTransaction {
  to: Address
  value: bigint
  data: `0x${string}`
  operation?: 0 | 1 // 0 = CALL, 1 = DELEGATE_CALL
  safeTxGas?: bigint
  baseGas?: bigint
  gasPrice?: bigint
  gasToken?: Address
  refundReceiver?: Address
  nonce?: bigint
}

/**
 * Encode function call for Safe transaction
 */
export function encodeSafeTransaction(
  _contractAddress: Address,
  _functionName: string,
  _args: unknown[],
  _abi: any[]
): `0x${string}` {
  // This would use viem's encodeFunctionData in production
  // For now, return placeholder
  return `0x${'0'.repeat(64)}` as `0x${string}`
}

/**
 * Validate Safe configuration
 */
export function validateSafeConfig(config: SafeConfig): { valid: boolean; error?: string } {
  if (!config.owners || config.owners.length === 0) {
    return { valid: false, error: 'At least one owner is required' }
  }

  if (config.threshold < 1) {
    return { valid: false, error: 'Threshold must be at least 1' }
  }

  if (config.threshold > config.owners.length) {
    return { valid: false, error: 'Threshold cannot exceed number of owners' }
  }

  // Check for duplicate owners
  const uniqueOwners = new Set(config.owners.map((o) => o.toLowerCase()))
  if (uniqueOwners.size !== config.owners.length) {
    return { valid: false, error: 'Duplicate owners are not allowed' }
  }

  return { valid: true }
}

/**
 * Calculate gas estimates for Safe transaction
 */
export function estimateSafeGas(
  _transaction: SafeTransaction,
  _owners: Address[],
  threshold: number
): {
  safeTxGas: bigint
  baseGas: bigint
  totalGas: bigint
} {
  // Basic gas estimation
  // In production, this would query the Safe contract or use actual gas estimation
  const baseTxGas = 21000n
  const safeTxGas = baseTxGas * BigInt(Math.max(1, threshold))
  const baseGas = 50000n // Base gas for Safe operations
  
  return {
    safeTxGas,
    baseGas,
    totalGas: safeTxGas + baseGas,
  }
}

/**
 * Format Safe address for display
 */
export function formatSafeAddress(address: Address): string {
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

/**
 * Generate Safe deployment salt
 */
export function generateSafeSalt(): string {
  return `${Date.now()}_${Math.random().toString(36).slice(2, 11)}`
}

/**
 * Check if address is a Safe wallet
 */
export async function isSafeWallet(_address: Address): Promise<boolean> {
  // In production, this would check if the address is a deployed Safe contract
  // For now, return false as placeholder
  return false
}

/**
 * Get Safe service URL from environment
 */
export function getSafeServiceUrl(): string {
  return import.meta.env.VITE_SAFE_SERVICE_URL || 'https://safe-transaction-mainnet.safe.global'
}

/**
 * Get Safe owners from deployed Safe
 */
export async function getSafeOwners(_safeAddress: Address): Promise<Address[]> {
  // In production, this would query the Safe contract or Safe Service API
  // For now, return empty array
  return []
}

/**
 * Get Safe threshold from deployed Safe
 */
export async function getSafeThreshold(_safeAddress: Address): Promise<number> {
  // In production, this would query the Safe contract or Safe Service API
  // For now, return 1
  return 1
}
