// Lending API Client
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080/api';

export interface CollateralInfo {
  tokenSymbol: string;
  balance: string;
  balanceUsd: number;
  collateralValue: number;
}

export interface LendingPosition {
  userAddress: string;
  walletAddress: string;
  suppliedBalance: string;
  suppliedBalanceUsd: number;
  borrowedBalance: string;
  borrowedBalanceUsd: number;
  collateralBalances: Record<string, CollateralInfo>;
  healthFactor: number;
  ltv: number;
  supplyAPY: number;
  borrowAPY: number;
}

export interface LendingStats {
  totalSuppliedUsd: number;
  totalBorrowedUsd: number;
  totalCollateralUsd: number;
  utilizationRate: number;
  avgSupplyAPY: number;
  avgBorrowAPY: number;
  totalUsers: number;
  activeBorrowers: number;
  totalTVL: number;
}

export interface LendingMarket {
  id: number;
  market_name: string;
  contract_address: string;
  chain_id: number;
  collateral_asset: string;
  borrow_collateral_factor: number;
  liquidate_collateral_factor: number;
  liquidation_penalty: number;
  supply_cap: number;
  base_supply_apy: number;
  base_borrow_apy: number;
  is_active: boolean;
}

export interface LendingAPYPoint {
  time: string;
  supply_apy: number;
  borrow_apy: number;
}

export interface LendingAPYHistory {
  history: LendingAPYPoint[];
  current_supply_apy: number;
  current_borrow_apy: number;
  apy_change: number;
  period: string;
}

export async function fetchLendingAPYHistory(
  period: '1W' | '1M' | '1Y' = '1W',
  chainId?: number
): Promise<LendingAPYHistory | null> {
  try {
    const params = new URLSearchParams({ period });
    if (chainId) params.append('chain_id', chainId.toString());
    const response = await fetch(`${API_BASE_URL}/lending/apy-history?${params}`, {
      cache: 'no-store',
    });
    if (!response.ok) return null;
    const data = await response.json();
    if (!data.success) return null;
    return data.data;
  } catch (error: unknown) {
    console.error('Error fetching lending APY history:', error);
    return null;
  }
}

export async function fetchLendingPosition(address: string): Promise<LendingPosition | null> {
  try {
    const response = await fetch(`${API_BASE_URL}/lending/position/${address}`, {
      cache: 'no-store',
    });
    if (!response.ok) return null;
    const data = await response.json();
    if (!data.success) return null;
    return data.data;
  } catch (error: unknown) {
    console.error('Error fetching lending position:', error);
    return null;
  }
}

export async function fetchLendingStats(): Promise<LendingStats | null> {
  try {
    const response = await fetch(`${API_BASE_URL}/lending/stats`, {
      cache: 'no-store',
    });
    if (!response.ok) return null;
    const data = await response.json();
    if (!data.success) return null;
    return data.data;
  } catch (error: unknown) {
    console.error('Error fetching lending stats:', error);
    return null;
  }
}

export async function fetchLendingMarkets(): Promise<LendingMarket[]> {
  try {
    const response = await fetch(`${API_BASE_URL}/lending/markets`, {
      cache: 'no-store',
    });
    if (!response.ok) return [];
    const data = await response.json();
    if (!data.success) return [];
    return data.data;
  } catch (error: unknown) {
    console.error('Error fetching lending markets:', error);
    return [];
  }
}

export async function notifySupplyCollateral(asset: string, amount: string, txHash?: string): Promise<void> {
  try {
    await fetch(`${API_BASE_URL}/lending/supply-collateral`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ asset, amount, tx_hash: txHash }),
    });
  } catch (error: unknown) {
    console.error('Error notifying supply collateral:', error);
  }
}

export async function notifyWithdrawCollateral(asset: string, amount: string, txHash?: string): Promise<void> {
  try {
    await fetch(`${API_BASE_URL}/lending/withdraw-collateral`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ asset, amount, tx_hash: txHash }),
    });
  } catch (error: unknown) {
    console.error('Error notifying withdraw collateral:', error);
  }
}

export async function notifyLendingBorrow(amount: string, txHash?: string): Promise<void> {
  try {
    await fetch(`${API_BASE_URL}/lending/borrow`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount, tx_hash: txHash }),
    });
  } catch (error: unknown) {
    console.error('Error notifying lending borrow:', error);
  }
}

export async function notifyLendingRepay(amount: string, txHash?: string): Promise<void> {
  try {
    await fetch(`${API_BASE_URL}/lending/repay`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount, tx_hash: txHash }),
    });
  } catch (error: unknown) {
    console.error('Error notifying lending repay:', error);
  }
}

export async function notifyLendingSupply(amount: string, txHash?: string): Promise<void> {
  try {
    await fetch(`${API_BASE_URL}/lending/supply`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount, tx_hash: txHash }),
    });
  } catch (error: unknown) {
    console.error('Error notifying lending supply:', error);
  }
}

export async function notifyLendingWithdraw(amount: string, txHash?: string): Promise<void> {
  try {
    await fetch(`${API_BASE_URL}/lending/withdraw`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount, tx_hash: txHash }),
    });
  } catch (error: unknown) {
    console.error('Error notifying lending withdraw:', error);
  }
}
