import path from 'path';

import AuthStorage from '@arcblock/did-connect-storage-nedb';
// @ts-ignore
import { BlockletService } from '@blocklet/sdk/service/auth';
import { getWallet } from '@blocklet/sdk/lib/wallet';
import { WalletAuthenticator } from '@blocklet/sdk/lib/wallet-authenticator';
import { WalletHandlers } from '@blocklet/sdk/lib/wallet-handler';
import type { Request } from 'express';
import type { LiteralUnion } from 'type-fest';
import type { WalletObject } from '@ocap/wallet';

import env from './env';
import logger from './logger';

export const wallet: WalletObject = getWallet();
export const ethWallet: WalletObject = getWallet('ethereum');
export const authenticator = new WalletAuthenticator();
export const handlers = new WalletHandlers({
  authenticator,
  tokenStorage: new AuthStorage({
    dbPath: path.join(env.dataDir, 'auth.db'),
    // @ts-ignore
    onload: console.warn,
  }),
});

export const blocklet = new BlockletService();

export async function getVaultAddress() {
  try {
    const vault = await blocklet.getVault();
    if (!vault) {
      return null;
    }
    return vault;
  } catch (error) {
    logger.info('get vault wallet failed', { error });
    return null;
  }
}

export type CallbackArgs = {
  request: Request & { context: Record<string, any> };
  userDid: string;
  userPk: string;
  didwallet: {
    os: LiteralUnion<'ios' | 'android' | 'web', string>;
    version: string;
    jwt: string;
  };
  extraParams: Record<string, any>;
  updateSession: Function;
  claims: any[];
  step?: number;
  challenge?: string;
  pathname?: string;
  baseUrl?: string;
};
