import { PacificaClient } from './PacificaClient'

export interface LeveragePayload {
  account: string
  symbol: string
  leverage: number
  agentWallet?: string
  expiryWindow?: number
}

export interface SubaccountPayload {
  mainAccount: string
  subAccount: string
  expiryWindow?: number
}

export class PacificaAccountAdapter {
  constructor(private client: PacificaClient) {}

  async info(account?: string) {
    const payload = await this.buildSignedPayload('get_account_info', {
      account: this.client.requireAccount(account),
    })
    const response = await this.client.post<any>(this.client.endpoints.accountInfo, payload, { skipHeaderSig: true })
    return response?.data ?? response
  }

  async balances(account?: string) {
    const response = await this.client.get<any>(this.client.endpoints.balances, {
      account: this.client.requireAccount(account),
    })
    return response?.data ?? response
  }

  async positions(account?: string) {
    const response = await this.client.get<any>(this.client.endpoints.positions, {
      account: this.client.requireAccount(account),
    })
    return response?.data ?? response
  }

  async updateLeverage(payload: LeveragePayload) {
    const body = await this.buildSignedPayload(
      'update_leverage',
      {
        account: payload.account,
        symbol: payload.symbol,
        leverage: payload.leverage,
        agent_wallet: payload.agentWallet,
      },
      payload.expiryWindow,
    )
    return await this.client.post(this.client.endpoints.leverage, body, { skipHeaderSig: true })
  }

  async createSubaccount(payload: SubaccountPayload) {
    const { mainAccount, subAccount, expiryWindow } = payload
    const timestamp = Date.now()
    const baseExpiry = expiryWindow ?? 30000
    const subSig = await this.client.signOperation(
      'subaccount_initiate',
      {
        account: mainAccount,
      },
      baseExpiry,
    )
    const mainSig = await this.client.signOperation(
      'subaccount_confirm',
      {
        signature: subSig.signature,
      },
      baseExpiry,
    )
    return await this.client.post(
      this.client.endpoints.subaccountCreate,
      {
        main_account: mainAccount,
        subaccount: subAccount,
        timestamp,
        expiry_window: baseExpiry,
        main_signature: mainSig.signature,
        sub_signature: subSig.signature,
      },
      { skipHeaderSig: true },
    )
  }

  private async buildSignedPayload(operation: string, data: Record<string, any>, expiryWindow = 30000) {
    const signed = await this.client.signOperation(operation, data, expiryWindow)
    return {
      ...data,
      timestamp: signed.timestamp,
      expiry_window: signed.expiryWindow,
      signature: signed.signature,
    }
  }
}
