/**
 * Investment Service
 * API client for investment accounts, products, transactions, and withdrawals
 */

import { apiClient } from '../lib/apiClient';

// apiClient baseURL is /api/v1, so prefix paths with /investment
const API_PREFIX = '/investment';

// ============================================================================
// Types
// ============================================================================

export interface Product {
  id: string;
  code: string;
  name: string;
  description: string;
  riskProfile: 'conservative' | 'moderate' | 'aggressive';
  targetReturnMin: number;
  targetReturnMax: number;
  maxDrawdown: number;
  minInvestment: number;
  managementFee: number;
  performanceFee: number;
  isActive: boolean;
}

export interface ProductPerformance {
  date: string;
  cumulativeReturn: number;
  dailyReturn: number;
}

export interface InvestmentAccount {
  id: string;
  accountNumber: string;
  productId: string;
  product: {
    code: string;
    name: string;
    riskProfile: string;
  };
  status: 'active' | 'suspended' | 'closed';
  balance: number;
  initialInvestment: number;
  totalDeposited: number;
  totalWithdrawn: number;
  totalEarnings: number;
  unrealizedPnl: number;
  unrealizedPnlPercent: number;
  openedAt: string;
  closedAt?: string;
}

export interface AccountSummary {
  totalBalance: number;
  totalEarnings: number;
  totalDeposited: number;
  totalWithdrawn: number;
  overallReturn: number;
  overallReturnPercent: number;
  accounts: InvestmentAccount[];
}

export interface Transaction {
  id: string;
  accountId: string;
  type: 'deposit' | 'withdrawal' | 'distribution' | 'fee' | 'adjustment';
  amount: number;
  balanceAfter: number;
  status: 'pending' | 'completed' | 'failed' | 'cancelled';
  description: string;
  reference?: string;
  createdAt: string;
  completedAt?: string;
}

export interface Withdrawal {
  id: string;
  accountId: string;
  amount: number;
  status: 'pending' | 'approved' | 'processing' | 'completed' | 'rejected';
  requestedAt: string;
  processedAt?: string;
  bankInfo?: {
    bankName: string;
    accountLast4: string;
  };
  cryptoInfo?: {
    network: string;
    addressLast8: string;
  };
  rejectionReason?: string;
}

export interface Distribution {
  id: string;
  accountId: string;
  amount: number;
  rate: number;
  balanceBefore: number;
  balanceAfter: number;
  distributedAt: string;
}

export interface AccountDetail extends InvestmentAccount {
  recentTransactions: Transaction[];
  recentDistributions: Distribution[];
  performanceHistory: Array<{
    date: string;
    balance: number;
    pnl: number;
  }>;
}

// ============================================================================
// API Functions - Products
// ============================================================================

export async function getProducts(riskProfile?: string): Promise<Product[]> {
  const params = riskProfile ? { riskProfile } : {};
  const response = await apiClient.get(`${API_PREFIX}/products`, { params });
  return response.data.data;
}

export async function getProductById(productId: string): Promise<Product> {
  const response = await apiClient.get(`${API_PREFIX}/products/${productId}`);
  return response.data.data;
}

export async function getProductPerformance(
  productId: string,
  period: 'week' | 'month' | '3months' | 'year' = 'month'
): Promise<ProductPerformance[]> {
  const response = await apiClient.get(`${API_PREFIX}/products/${productId}/performance`, {
    params: { period },
  });
  return response.data.data;
}

// ============================================================================
// API Functions - Accounts
// ============================================================================

export async function getUserAccounts(): Promise<InvestmentAccount[]> {
  const response = await apiClient.get(`${API_PREFIX}/accounts`);
  return response.data.data;
}

export async function getAccountSummary(): Promise<AccountSummary> {
  const response = await apiClient.get(`${API_PREFIX}/accounts/summary`);
  return response.data.data;
}

export async function getAccountById(accountId: string): Promise<AccountDetail> {
  const response = await apiClient.get(`${API_PREFIX}/accounts/${accountId}`);
  return response.data.data;
}

export async function createAccount(productId: string, initialDeposit: number): Promise<InvestmentAccount> {
  const response = await apiClient.post(`${API_PREFIX}/accounts`, { productId, initialDeposit });
  return response.data.data;
}

export async function closeAccount(accountId: string): Promise<void> {
  await apiClient.post(`${API_PREFIX}/accounts/${accountId}/close`);
}

// ============================================================================
// API Functions - Transactions
// ============================================================================

export async function getTransactions(
  accountId: string,
  options?: {
    type?: string;
    status?: string;
    limit?: number;
    offset?: number;
  }
): Promise<{ transactions: Transaction[]; total: number }> {
  const response = await apiClient.get(`${API_PREFIX}/accounts/${accountId}/transactions`, {
    params: options,
  });
  return response.data.data;
}

export async function createDeposit(accountId: string, amount: number): Promise<Transaction> {
  const response = await apiClient.post(`${API_PREFIX}/accounts/${accountId}/deposit`, { amount });
  return response.data.data;
}

export async function createWithdrawal(
  accountId: string,
  amount: number,
  destination: {
    bankInfo?: { bankName: string; accountNumber: string; routingNumber: string };
    cryptoInfo?: { network: string; address: string };
  }
): Promise<Withdrawal> {
  const response = await apiClient.post(`${API_PREFIX}/accounts/${accountId}/withdraw`, {
    amount,
    ...destination,
  });
  return response.data.data;
}

// ============================================================================
// API Functions - Distributions
// ============================================================================

export async function getDistributions(accountId: string): Promise<Distribution[]> {
  const response = await apiClient.get(`${API_PREFIX}/accounts/${accountId}/distributions`);
  return response.data.data;
}

// ============================================================================
// API Functions - Withdrawals
// ============================================================================

export async function getWithdrawals(status?: string): Promise<Withdrawal[]> {
  const params = status ? { status } : {};
  const response = await apiClient.get(`${API_PREFIX}/withdrawals`, { params });
  return response.data.data;
}

export default {
  // Products
  getProducts,
  getProductById,
  getProductPerformance,
  // Accounts
  getUserAccounts,
  getAccountSummary,
  getAccountById,
  createAccount,
  closeAccount,
  // Transactions
  getTransactions,
  createDeposit,
  createWithdrawal,
  // Distributions
  getDistributions,
  // Withdrawals
  getWithdrawals,
};
