import { Contract, ethers } from 'ethers';
import { rpcUrls } from './constants';
import { Options } from './types';
import { nftAbi } from './abi/index';



export async function getImage(options: Options): Promise<string> {
	const {  address, tokenId, network } = options;
  const rpcUrl = rpcUrls[network];

  if (!rpcUrl) {
    throw new Error(`Invalid network: ${network}`);
  }
  
  const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
  const contract = new Contract(JSON.stringify(nftAbi), address, provider);
  
  let metadata: any;


  // const owner = await contract.functions.ownerOf(tokenId).call();
  // if (owner !== provider.getSigner().getAddress()) {
  //   throw new Error(`Token ${tokenId} is not owned by you`);
  // }
  
  if (tokenId) {
    metadata = await contract.tokenId(tokenId);
  } else {
    const totalSupply = await contract.totalSupply();
    const totalSupplyNumber = totalSupply.toNumber();
    const randomId = Math.floor(Math.random() * totalSupplyNumber);
    metadata = await contract.functions.tokenId(randomId);
  }
  
  let imageUrl = metadata.image;

	if (!imageUrl.startsWith('http')) {
  		imageUrl = `https://${imageUrl}`;
	}

	return imageUrl;

}


  