/**
 * 共管钱包服务
 * 处理共管钱包会话创建、状态查询等操作
 */

import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';

// ============================================
// 类型定义
// ============================================

export interface ThresholdConfig {
  t: number;
  n: number;
}

export interface Participant {
  partyId: string;
  name: string;
  status: 'waiting' | 'ready' | 'processing' | 'completed' | 'failed';
  joinedAt: string;
}

export interface CoManagedWalletSession {
  sessionId: string;
  walletName: string;
  threshold: ThresholdConfig;
  inviteCode: string;
  inviteUrl: string;
  status: 'waiting' | 'ready' | 'processing' | 'completed' | 'failed' | 'cancelled';
  participants: Participant[];
  currentRound: number;
  totalRounds: number;
  publicKey?: string;
  error?: string;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

export interface CoManagedWallet {
  id: string;
  sessionId: string;
  name: string;
  publicKey: string;
  threshold: ThresholdConfig;
  participantCount: number;
  participants: Array<{ partyId: string; name: string }>;
  createdAt: string;
  createdBy: string;
}

// ============================================
// 请求参数类型
// ============================================

export interface CreateSessionParams {
  walletName: string;
  thresholdT: number;
  thresholdN: number;
  initiatorName: string;
  partyId?: string; // 发起者的 party ID (Admin-Web 作为参与方时使用)
}

export interface JoinSessionParams {
  participantName: string;
  partyId: string;
}

export interface UpdateSessionStatusParams {
  publicKey?: string;
  error?: string;
}

export interface ListParams {
  page?: number;
  pageSize?: number;
  status?: string;
}

// ============================================
// 响应类型
// ============================================

export interface CreateSessionResponse {
  success: boolean;
  session: CoManagedWalletSession;
}

export interface ValidateInviteCodeResponse {
  valid: boolean;
  session?: {
    sessionId: string;
    walletName: string;
    threshold: ThresholdConfig;
    initiator: string;
    createdAt: string;
    currentParticipants: number;
  };
  error?: string;
}

export interface SessionListResponse {
  items: CoManagedWalletSession[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface WalletListResponse {
  items: CoManagedWallet[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// ============================================
// API 服务
// ============================================

export const coManagedWalletService = {
  /**
   * 创建共管钱包会话
   */
  createSession: async (params: CreateSessionParams): Promise<CreateSessionResponse> => {
    return apiClient.post(API_ENDPOINTS.CO_MANAGED_WALLETS.CREATE_SESSION, params);
  },

  /**
   * 获取会话详情
   */
  getSession: async (sessionId: string): Promise<CoManagedWalletSession> => {
    return apiClient.get(API_ENDPOINTS.CO_MANAGED_WALLETS.SESSION_DETAIL(sessionId));
  },

  /**
   * 获取会话列表
   */
  listSessions: async (params?: ListParams): Promise<SessionListResponse> => {
    return apiClient.get(API_ENDPOINTS.CO_MANAGED_WALLETS.CREATE_SESSION, { params });
  },

  /**
   * 验证邀请码
   */
  validateInviteCode: async (inviteCode: string): Promise<ValidateInviteCodeResponse> => {
    return apiClient.post(`${API_ENDPOINTS.CO_MANAGED_WALLETS.CREATE_SESSION}/validate-invite`, {
      inviteCode,
    });
  },

  /**
   * 加入会话
   */
  joinSession: async (
    sessionId: string,
    params: JoinSessionParams
  ): Promise<CoManagedWalletSession> => {
    return apiClient.post(
      `${API_ENDPOINTS.CO_MANAGED_WALLETS.SESSION_DETAIL(sessionId)}/join`,
      params
    );
  },

  /**
   * 开始密钥生成
   */
  startKeygen: async (sessionId: string): Promise<CoManagedWalletSession> => {
    return apiClient.post(
      `${API_ENDPOINTS.CO_MANAGED_WALLETS.SESSION_DETAIL(sessionId)}/start-keygen`
    );
  },

  /**
   * 更新会话状态
   */
  updateSessionStatus: async (
    sessionId: string,
    status: string,
    params?: UpdateSessionStatusParams
  ): Promise<CoManagedWalletSession> => {
    return apiClient.put(
      `${API_ENDPOINTS.CO_MANAGED_WALLETS.SESSION_DETAIL(sessionId)}/status`,
      { status, ...params }
    );
  },

  /**
   * 取消会话
   */
  cancelSession: async (sessionId: string): Promise<void> => {
    return apiClient.delete(API_ENDPOINTS.CO_MANAGED_WALLETS.SESSION_DETAIL(sessionId));
  },

  /**
   * 获取钱包列表
   */
  listWallets: async (params?: ListParams): Promise<WalletListResponse> => {
    return apiClient.get(API_ENDPOINTS.CO_MANAGED_WALLETS.LIST, { params });
  },

  /**
   * 获取钱包详情
   */
  getWallet: async (walletId: string): Promise<CoManagedWallet> => {
    return apiClient.get(API_ENDPOINTS.CO_MANAGED_WALLETS.WALLET_DETAIL(walletId));
  },
};

export default coManagedWalletService;
