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

interface InstantlyCredentials {
  apiKey: string
}

export interface BulkDeleteLeadsParams {
  ids?: string[]
  campaign_id?: string
  list_id?: string
  limit?: number
}

export interface BulkDeleteLeadsResult {
  deleted_count: number
}

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

/**
 * Bulk delete leads from Instantly
 *
 * Deletes leads matching the provided filters. At least one of ids,
 * campaign_id, or list_id is recommended to avoid unintended broad deletions.
 *
 * @param credentials - Instantly API key
 * @param params - Deletion filters (IDs, campaign, list, or limit)
 * @param context - Execution context for logging
 * @returns Count of deleted leads
 */
export async function bulkDeleteLeads(
  credentials: InstantlyCredentials,
  params: BulkDeleteLeadsParams,
  context?: ExecutionContext
): Promise<BulkDeleteLeadsResult> {
  const { apiKey } = credentials
  const { ids, campaign_id, list_id, limit } = params

  const body: Record<string, unknown> = {}
  if (ids && ids.length > 0) body.ids = ids
  if (campaign_id) body.campaign_id = campaign_id
  if (list_id) body.list_id = list_id
  if (limit !== undefined) body.limit = limit

  const url = `${INSTANTLY_API_BASE}/leads`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Bulk deleting leads: ids_count=${ids?.length} campaign_id=${campaign_id} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const deleted_count = Number(response.deleted_count ?? response.count ?? 0)

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Bulk delete leads complete: deleted_count=${deleted_count} executionId=${context.executionId}`
    )
  }

  return { deleted_count }
}
