import { isAddress } from "viem";
import { DUMMY_ADDRESS, DUMMY_SOLANA_ADDRESS } from "./constants";
import { isPublicKey } from "./isPublicKey";
import { isSolana } from "./isSolana";

interface GetValidAddressParams {
	chainId: number | null;
	address: string | null;
	fallbackAddress: string | null;
}

/**
 * Returns a valid address based on the chain type (Solana or EVM)
 * @param chainId - The chain ID to check
 * @param address - The address to validate
 * @param fallbackAddress - Optional fallback address to use if the main address is invalid
 * @returns A valid address for the given chain type
 */
export const getValidAddress = ({
	chainId,
	address,
	fallbackAddress,
}: GetValidAddressParams): string => {
	if (!chainId) return DUMMY_ADDRESS;

	if (isSolana(chainId)) {
		// For Solana chains
		if (address && isPublicKey(address)) {
			return address;
		}
		// Validate fallback address for Solana
		if (fallbackAddress && isPublicKey(fallbackAddress)) {
			return fallbackAddress;
		}
		return DUMMY_SOLANA_ADDRESS;
	}
	// For EVM chains
	if (address && isAddress(address)) {
		return address;
	}
	// Validate fallback address for EVM
	if (fallbackAddress && isAddress(fallbackAddress)) {
		return fallbackAddress;
	}
	return DUMMY_ADDRESS;
};
