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

interface InstantlyCredentials {
  apiKey: string
}

export interface DeleteCampaignParams {
  campaign_id: string
}

export interface DeleteCampaignResult {
  success: boolean
  campaign_id: string
}

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

/**
 * Delete an Instantly campaign
 *
 * Permanently deletes a campaign and all associated data. This action cannot be undone.
 * Use for cleaning up test/draft campaigns or removing campaigns that are no longer needed.
 *
 * @param credentials - Instantly API key
 * @param params - Campaign ID to delete
 * @param context - Execution context for logging
 * @returns Success status and campaign ID
 */
export async function deleteCampaign(
  credentials: InstantlyCredentials,
  params: DeleteCampaignParams,
  context?: ExecutionContext
): Promise<DeleteCampaignResult> {
  const { apiKey } = credentials
  const { campaign_id } = params

  if (!campaign_id) {
    throw new ToolingError('validation_error', 'Missing required parameter: campaign_id', {
      integration: 'instantly',
      method: 'deleteCampaign'
    })
  }

  const deleteUrl = `${INSTANTLY_API_BASE}/campaigns/${campaign_id}`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Deleting campaign: campaign_id=${campaign_id} executionId=${context.executionId}`
    )
  }

  await withRetry(async () => {
    const res = await fetch(deleteUrl, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${apiKey}`
      }
    })

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

    // DELETE may return empty body
    const text = await res.text()
    return text ? JSON.parse(text) : {}
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Campaign deleted successfully: campaign_id=${campaign_id} executionId=${context.executionId}`
    )
  }

  return {
    success: true,
    campaign_id
  }
}
