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

interface ApifyCredentials {
  apiToken: string
}

export interface GetDatasetItemsParams {
  datasetId: string
  maxItems?: number
  offset?: number
}

export interface GetDatasetItemsResult {
  items: unknown[]
  totalCount: number
}

const APIFY_API_BASE = 'https://api.apify.com/v2'

/**
 * Fetch items from an Apify dataset
 *
 * Retrieves items from a dataset by ID. Useful for:
 * - Recovering data after a runActor timeout (actor keeps running on Apify)
 * - Fetching results from a previously completed run
 * - Paginating through large datasets with offset/maxItems
 *
 * @param credentials - Apify API token
 * @param params - Dataset ID and optional pagination
 * @param context - Execution context for logging
 * @returns Dataset items and total count
 */
export async function getDatasetItems(
  credentials: ApifyCredentials,
  params: GetDatasetItemsParams,
  context?: ExecutionContext
): Promise<GetDatasetItemsResult> {
  const { apiToken } = credentials
  const { datasetId, maxItems, offset } = params

  if (!datasetId) {
    throw new ToolingError('validation_error', 'Missing required parameter: datasetId', {
      integration: 'apify',
      method: 'getDatasetItems'
    })
  }

  let datasetUrl = `${APIFY_API_BASE}/datasets/${datasetId}/items?format=json`
  if (maxItems) {
    datasetUrl += `&limit=${maxItems}`
  }
  if (offset) {
    datasetUrl += `&offset=${offset}`
  }

  if (context?.logger) {
    context.logger.info(
      `[ApifyAdapter] Fetching dataset items: organizationId=${context.organizationId} executionId=${context.executionId} datasetId=${datasetId} maxItems=${maxItems} offset=${offset}`
    )
  }

  const datasetResponse = await withRetry(async () => {
    const response = await fetch(datasetUrl, {
      headers: { Authorization: `Bearer ${apiToken}` }
    })

    if (!response.ok) {
      throw await createHttpError(response, {
        integration: 'apify',
        method: 'getDatasetItems',
        datasetId
      })
    }

    return response.json()
  }, DEFAULT_RETRY_POLICY)

  const items = Array.isArray(datasetResponse) ? datasetResponse : []

  if (context?.logger) {
    context.logger.info(
      `[ApifyAdapter] Dataset items fetched: organizationId=${context.organizationId} executionId=${context.executionId} datasetId=${datasetId} itemCount=${items.length}`
    )
  }

  return {
    items,
    totalCount: items.length
  }
}
