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

interface InstantlyCredentials {
  apiKey: string
}

export interface ListLeadsParams {
  campaign_id?: string
  email?: string
  limit?: number
  starting_after?: string
}

export interface ListLeadsResult {
  items: Array<{
    id: string
    email: string
    first_name?: string
    last_name?: string
    company_name?: string
    status: string
    campaign_id?: string
    timestamp_created?: string
  }>
  next_starting_after?: string
}

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

/**
 * List leads in Instantly with optional filtering and pagination
 *
 * Uses a POST endpoint per Instantly API design — complex filter arguments
 * are expressed as a JSON body rather than query parameters.
 *
 * @param credentials - Instantly API key
 * @param params - Optional filters and pagination cursor
 * @param context - Execution context for logging
 * @returns Paginated list of leads
 */
export async function listLeads(
  credentials: InstantlyCredentials,
  params: ListLeadsParams,
  context?: ExecutionContext
): Promise<ListLeadsResult> {
  const { apiKey } = credentials
  const { campaign_id, email, limit, starting_after } = params

  const body: Record<string, unknown> = {}
  if (campaign_id) body.campaign = campaign_id
  if (email) body.contacts = [email]
  if (limit !== undefined) body.limit = limit
  if (starting_after) body.starting_after = starting_after

  const url = `${INSTANTLY_API_BASE}/leads/list`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Listing leads: campaign_id=${campaign_id} email=${email} limit=${limit} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  const response = await withRetry(async () => {
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    })

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const rawItems: Array<Record<string, unknown>> = Array.isArray(response.items)
    ? response.items
    : Array.isArray(response)
      ? response
      : []

  const items = rawItems.map((item) => ({
    id: String(item.id ?? ''),
    email: String(item.email ?? ''),
    first_name: item.first_name !== undefined ? String(item.first_name) : undefined,
    last_name: item.last_name !== undefined ? String(item.last_name) : undefined,
    company_name: item.company_name !== undefined ? String(item.company_name) : undefined,
    status: String(item.status ?? ''),
    campaign_id: item.campaign_id !== undefined ? String(item.campaign_id) : undefined,
    timestamp_created: item.timestamp_created !== undefined ? String(item.timestamp_created) : undefined
  }))

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Leads listed: count=${items.length} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  return {
    items,
    next_starting_after: response.next_starting_after !== undefined ? String(response.next_starting_after) : undefined
  }
}
