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 RemoveFromSubsequenceParams {
  lead_email: string
  campaign_id: string
}

export interface RemoveFromSubsequenceResult {
  success: boolean
  lead_email: string
  campaign_id: string
}

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

/**
 * Remove a lead from a campaign subsequence
 *
 * Stops a lead from receiving further emails in a campaign sequence.
 * Useful for removing leads who have replied or are no longer qualified.
 *
 * @param credentials - Instantly API key
 * @param params - Lead email and campaign ID
 * @param context - Execution context for logging
 * @returns Removal confirmation
 */
export async function removeFromSubsequence(
  credentials: InstantlyCredentials,
  params: RemoveFromSubsequenceParams,
  context?: ExecutionContext
): Promise<RemoveFromSubsequenceResult> {
  const { apiKey } = credentials
  const { lead_email, campaign_id } = params

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

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

  const removeUrl = `${INSTANTLY_API_BASE}/leads/subsequence/remove`

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Removing lead from subsequence: lead_email=${lead_email} campaign_id=${campaign_id} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Lead removed successfully: lead_email=${lead_email} campaign_id=${campaign_id} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  return {
    success: true,
    lead_email,
    campaign_id
  }
}
