import { configureChains, createConfig } from '@wagmi/core';
import { gnosis } from '@wagmi/core/chains';
import { publicProvider } from '@wagmi/core/providers/public';
import { InjectedConnector } from '@wagmi/core/connectors/injected';
import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect';
import { jsonRpcProvider } from '@wagmi/core/providers/jsonRpc';
import { createMessage } from '$lib/services/messages/messages';

export interface ProviderData {
	walletConnectId: string;
}

const chronicleChain = {
	id: 175177,
	name: 'Chronicle',
	network: 'chronicle',

	nativeCurrency: {
		decimals: 18,
		name: 'Chronicle - Lit Protocol Testnet',
		symbol: 'LIT'
	},
	rpcUrls: {
		default: {
			http: ['https://chain-rpc.litprotocol.com/http']
		},
		public: {
			http: ['https://chain-rpc.litprotocol.com/http']
		}
	},
	blockExplorers: {
		default: {
			name: 'Chronicle - Lit Protocol Testnet',
			url: 'https://chain.litprotocol.com'
		}
	},
	testnet: true
};

export function initChainProvider(data: ProviderData) {
	createMessage({
		text: 'Provider setup initialization started...',
		sender: '$lib/services/provider.ts',
		type: 'SYSTEM'
	});

	const { chains, publicClient } = configureChains(
		[chronicleChain, gnosis],
		[
			jsonRpcProvider({
				rpc: (chain) => ({ http: chain.rpcUrls.default.http[0] })
			}),
			jsonRpcProvider({
				rpc: () => ({
					http: `https://rpc.gnosischain.com/`,
					wss: `wss://rpc.gnosischain.com/wss`
				})
			}),
			publicProvider()
		]
	);

	createMessage({
		text: 'Chains configured successfully...',
		sender: '$lib/services/provider.ts',
		type: 'SYSTEM'
	});

	createConfig({
		autoConnect: true,
		connectors: [
			new InjectedConnector({ chains }),
			new WalletConnectConnector({
				chains,
				options: {
					projectId: data.walletConnectId
				}
			})
		],
		publicClient
	});

	createMessage({
		text: 'Chain Provider configuration created and autoConnect enabled...',
		sender: '$lib/services/provider.ts',
		type: 'SYSTEM'
	});
}

