#!/usr/bin/env npx tsx
/**
 * Pacifica凭据管理服务测试脚本
 */

import fs from 'fs';
import { PacificaCredentialService } from './src/app/credential-service.js';

async function testCredentialService() {
  console.log('🧪 开始测试Pacifica凭据管理服务');

  // 创建测试配置
  const testConfig = {
    pacifica: [
      {
        accountId: 'test-account',
        alias: '测试账户',
        privateKey: '5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3', // 测试私钥
        environment: 'development'
      }
    ]
  };

  const configPath = './credentials.test.json';
  fs.writeFileSync(configPath, JSON.stringify(testConfig, null, 2));

  let service: PacificaCredentialService | undefined;

  try {
    // 启动服务
    service = new PacificaCredentialService(configPath, 3002);
    await service.start();

    console.log('✅ 服务启动成功');

    // 测试1：获取服务状态
    console.log('\n📊 测试1: 获取服务状态');
    const statusResponse = await fetch('http://localhost:3002/api/v1/status');
    const statusData = await statusResponse.json();
    console.log('状态:', statusData.data.status);
    console.log('账户数量:', statusData.data.accounts.total);

    // 测试2：执行签名
    console.log('\n🔏 测试2: 执行Pacifica签名');
    const signRequest = {
      platformId: 'pacifica',
      accountId: 'test-account',
      data: {
        instruction: {
          type: 'place_order',
          market: 'BTC-USD',
          side: 'bid',
          amount: '0.001',
          price: '65000'
        },
        nonce: Date.now()
      }
    };

    const signResponse = await fetch('http://localhost:3002/api/v1/sign', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(signRequest)
    });

    const signData = await signResponse.json();
    console.log('签名成功:', signData.success);
    console.log('算法:', signData.data.algorithm);
    console.log('签名长度:', signData.data.signature.length);
    console.log('执行时间:', signData.data.metadata.executionTimeMs, 'ms');

    // 测试3：获取账户列表
    console.log('\n📋 测试3: 获取账户列表');
    const accountsResponse = await fetch('http://localhost:3002/api/v1/accounts?platform=pacifica');
    const accountsData = await accountsResponse.json();
    console.log('账户数量:', accountsData.data.total);
    console.log('第一个账户ID:', accountsData.data.accounts[0].accountId);

    console.log('\n✅ 所有测试通过!');

  } catch (error) {
    console.error('❌ 测试失败:', error);
  } finally {
    // 清理
    if (service) {
      await service.stop();
    }
    if (fs.existsSync(configPath)) {
      fs.unlinkSync(configPath);
    }
    console.log('🧹 清理完成');
  }
}

// 运行测试
if (import.meta.url === `file://${process.argv[1]}`) {
  testCredentialService().catch(console.error);
}