/**
 * 统一签名器实现
 */

import { Platform, SignResult, Credentials } from './types';

export interface ISignerStrategy {
  platform: Platform;
  sign(message: Uint8Array, credentials: Credentials): Promise<string>;
  verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean>;
}

export interface ISigner {
  registerStrategy(platform: Platform, strategy: ISignerStrategy): void;
  addAccount(accountId: string, platform: Platform, credentials: Credentials): void;
  sign(accountId: string, message: Uint8Array): Promise<SignResult>;
  verify(accountId: string, message: Uint8Array, signature: string): Promise<boolean>;
}

export class Signer implements ISigner {
  private strategies = new Map<Platform, ISignerStrategy>();
  private accounts = new Map<string, { platform: Platform; credentials: Credentials }>();

  public registerStrategy(platform: Platform, strategy: ISignerStrategy): void {
    this.strategies.set(platform, strategy);
  }

  public addAccount(accountId: string, platform: Platform, credentials: Credentials): void {
    this.accounts.set(accountId, { platform, credentials });
  }

  public async sign(accountId: string, message: Uint8Array): Promise<SignResult> {
    const startTime = Date.now();

    try {
      const account = this.accounts.get(accountId);
      if (!account) {
        return {
          success: false,
          algorithm: 'unknown',
          timestamp: new Date(),
          error: `Account not found: ${accountId}`,
        };
      }

      const strategy = this.strategies.get(account.platform);
      if (!strategy) {
        return {
          success: false,
          algorithm: 'unknown',
          timestamp: new Date(),
          error: `No strategy for platform: ${account.platform}`,
        };
      }

      const signature = await strategy.sign(message, account.credentials);
      const signTime = Date.now() - startTime;

      return {
        success: true,
        signature,
        algorithm: this.getAlgorithmForPlatform(account.platform),
        timestamp: new Date(),
      };

    } catch (error) {
      return {
        success: false,
        algorithm: 'unknown',
        timestamp: new Date(),
        error: (error as Error).message,
      };
    }
  }

  public async verify(accountId: string, message: Uint8Array, signature: string): Promise<boolean> {
    try {
      const account = this.accounts.get(accountId);
      if (!account) return false;

      const strategy = this.strategies.get(account.platform);
      if (!strategy) return false;

      return await strategy.verify(message, signature, ''); // 公钥需要从策略获取

    } catch (error) {
      return false;
    }
  }

  private getAlgorithmForPlatform(platform: Platform): string {
    switch (platform) {
      case Platform.PACIFICA: return 'ed25519';
      case Platform.ASTER: return 'ecdsa-ethereum';
      case Platform.BINANCE: return 'hmac-sha256';
      default: return 'unknown';
    }
  }
}