import type { IRelayPKP } from '@lit-protocol/types';
import type { IProvider } from '$lib/services/provider/IProvider';
import { createMessage } from '$lib/services/messages/messages';

export async function mintPkp(provider: IProvider, authMethod: any): Promise<IRelayPKP> {
    createMessage({
        text: 'Minting started...',
        sender: '$lib/components/GoogleAuth.svelte',
        type: 'SYSTEM'
    });

    const txHash: string = await provider.mintPKPThroughRelayer(authMethod);
    const response = await provider.relay.pollRequestUntilTerminalState(txHash);
    if (response.status !== 'Succeeded') {
        throw new Error('Minting failed');
    }
    const newPKP: IRelayPKP = {
        tokenId: response.pkpTokenId,
        publicKey: response.pkpPublicKey,
        ethAddress: response.pkpEthAddress
    };

    createMessage({
        text: 'Minted a new PKP.',
        sender: '$lib/components/GoogleAuth.svelte',
        type: 'SYSTEM'
    });

    return newPKP;
}
