import { withRetry, createHttpError, DEFAULT_RETRY_POLICY } from '../../../../../../../../../platform/resilience'
import type { ExecutionContext } from '../../../../../../../base/types'

interface InstantlyCredentials {
  apiKey: string
}

export interface GetAccountHealthParams {
  limit?: number
  starting_after?: string
}

export interface AccountHealthEntry {
  id: string
  email: string
  status: string
  warmup_enabled: boolean
  health_score?: number
  [key: string]: unknown
}

export interface GetAccountHealthResult {
  accounts: AccountHealthEntry[]
  next_starting_after?: string
}

const INSTANTLY_API_BASE = 'https://api.instantly.ai/api/v2'

/**
 * Get account health for Instantly sending accounts
 *
 * Retrieves a paginated list of sending accounts with their health status,
 * warmup state, and health scores. Supports cursor-based pagination via
 * starting_after.
 *
 * @param credentials - Instantly API key
 * @param params - Optional limit and pagination cursor
 * @param context - Execution context for logging
 * @returns List of accounts with health data and optional next page cursor
 */
export async function getAccountHealth(
  credentials: InstantlyCredentials,
  params: GetAccountHealthParams,
  context?: ExecutionContext
): Promise<GetAccountHealthResult> {
  const { apiKey } = credentials
  const { limit, starting_after } = params

  const queryParams = new URLSearchParams()
  if (limit) queryParams.set('limit', String(limit))
  if (starting_after) queryParams.set('starting_after', starting_after)

  const accountsUrl = `${INSTANTLY_API_BASE}/accounts${queryParams.toString() ? `?${queryParams.toString()}` : ''}`

  if (context?.logger) {
    context.logger.info(`[InstantlyAdapter] Fetching account health: limit=${limit} executionId=${context.executionId}`)
  }

  const response = await withRetry(async () => {
    const res = await fetch(accountsUrl, {
      headers: {
        Authorization: `Bearer ${apiKey}`
      }
    })

    if (!res.ok) {
      throw await createHttpError(res, {
        integration: 'instantly',
        method: 'getAccountHealth',
        organizationId: context?.organizationId
      })
    }

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const rawData = response.data ?? response
  const accounts: AccountHealthEntry[] = Array.isArray(rawData) ? rawData : rawData?.items || rawData?.accounts || []
  const next_starting_after = response.next_starting_after || response.data?.next_starting_after

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Account health fetched: account_count=${accounts.length} executionId=${context.executionId}`
    )
  }

  return {
    accounts,
    ...(next_starting_after ? { next_starting_after } : {})
  }
}
