import { checkAndSignAuthMessage } from '@lit-protocol/lit-node-client';
import { LOCAL_STORAGE_KEYS } from '@lit-protocol/constants';

function createMessage({ text, sender, type }: { text: string; sender: string; type: string }) {
    console.log(`[${type}] - ${sender} - ${text}`);
}

export async function generateAuthSig(): Promise<any> {
    createMessage({
        text: "Attempting to generate AuthSig using MetaMask.",
        sender: '$lib/services/authWithMetamask/authWithMetamask.ts',
        type: 'SYSTEM'
    });

    try {
        const authSig = await checkAndSignAuthMessage({ chain: 'xdai' });

        createMessage({
            text: "AuthSig generated and storing in local storage.",
            sender: '$lib/services/authWithMetamask/authWithMetamask.ts',
            type: 'SYSTEM'
        });

        localStorage.setItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE, JSON.stringify(authSig));
        return authSig;
    } catch (err) {
        console.error(err);

        createMessage({
            text: `Failed to sign auth message: ${err.message}`,
            sender: '$lib/services/authWithMetamask/authWithMetamask.ts',
            type: 'ERROR'
        });

        throw new Error(`Failed to sign auth message: ${err.message}`);
    }
}

export function getStoredAuthSig(): any | null {
    createMessage({
        text: "Fetching stored AuthSig from local storage.",
        sender: '$lib/services/authWithMetamask/authWithMetamask.ts',
        type: 'SYSTEM'
    });

    const storedAuthSig = localStorage.getItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
    if (storedAuthSig) {
        return JSON.parse(storedAuthSig);
    }
    return null;
}

export function logout(): void {
    createMessage({
        text: "Clearing AuthSig from local storage.",
        sender: '$lib/services/authWithMetamask/authWithMetamask.ts',
        type: 'SYSTEM'
    });

    localStorage.removeItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
}
