import { getStoredAuthSig } from '$lib/services/authWithMetamask/authWithMetamask';
import { PKPEthersWallet } from '@lit-protocol/pkp-ethers';
import { createMessage } from '$lib/services/messages/messages';

// Use a variable to keep track of whether the wallet has been connected or not
let isWalletConnected = false;

export async function connectWallet(pkpPubKey: string, rpcURL: string = 'https://rpc.gnosischain.com/'): Promise<PKPEthersWallet | null> {
    if (isWalletConnected) {
        createMessage({
            text: 'Attempted to connect PKPEthersWallet, but it is already connected.',
            sender: '$lib/services/wallet/wallet.ts',
            type: 'INFO'
        });
        return null;
    }

    const authSig = getStoredAuthSig();

    if (!authSig) {
        createMessage({
            text: 'No authSig parsed from local storage.',
            sender: '$lib/services/wallet/wallet.ts',
            type: 'ERROR'
        });
        alert('No authSig parsed from local storage');
        return null;
    }

    createMessage({
        text: `Connecting PKPEthersWallet with provided pkpPubKey using RPC: ${rpcURL}`,
        sender: '$lib/services/wallet/wallet.ts',
        type: 'SYSTEM'
    });

    const pkpWallet = new PKPEthersWallet({
        controllerAuthSig: authSig,
        pkpPubKey,
        rpc: rpcURL
    });

    await pkpWallet.init();

    createMessage({
        text: 'PKPEthersWallet connected successfully.',
        sender: '$lib/services/wallet/wallet.ts',
        type: 'SUCCESS'
    });

    isWalletConnected = true;

    return pkpWallet;
}

// Function to return the authSig
export function signSession(): string | null {
    const authSig = getStoredAuthSig();
    if (!authSig) {
        createMessage({
            text: 'No authSig found in local storage.',
            sender: '$lib/services/wallet/wallet.ts',
            type: 'ERROR'
        });
        return null;
    }

    return authSig;
}
