/**
 * Pacifica签名策略适配器
 *
 * 将PacificaSigner适配为ISignerStrategy接口
 */

import { ISignerStrategy } from '@/core/Signer';
import { Platform, Credentials, PacificaCredentials } from '@/core/types';
import { PacificaSigner, PacificaOrderType } from './PacificaSigner';

export class PacificaSignerStrategy implements ISignerStrategy {
  public readonly platform = Platform.PACIFICA;
  private pacificaSigner = new PacificaSigner();

  public async sign(message: Uint8Array, credentials: Credentials): Promise<string> {
    if (credentials.type !== 'pacifica') {
      throw new Error('Invalid credentials type for Pacifica signer');
    }

    const pacificaCreds = credentials as PacificaCredentials;

    // 为PacificaSigner添加账户
    const tempAccountId = `temp_${Date.now()}`;
    this.pacificaSigner.addAccount(tempAccountId, pacificaCreds.privateKey);

    try {
      // 执行签名
      const result = await this.pacificaSigner.signOrder({
        accountId: tempAccountId,
        message,
        orderType: PacificaOrderType.LIMIT, // 默认订单类型
      });

      if (!result.success) {
        throw new Error(result.error || 'Signing failed');
      }

      return result.signature;
    } finally {
      // 清理临时账户
      this.pacificaSigner.removeAccount(tempAccountId);
    }
  }

  public async verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean> {
    const result = await this.pacificaSigner.verifySignature({
      accountId: 'verify',
      message,
      signature,
      publicKey,
    });

    return result.success && (result.isValid ?? false);
  }
}