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 UpdateInterestStatusParams {
  lead_email: string
  interest_value: number
  campaign_id?: string
  disable_auto_interest?: boolean
}

export interface UpdateInterestStatusResult {
  success: boolean
  lead_email: string
}

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

/**
 * Update interest status of a lead in Instantly.ai
 *
 * Sets the lead's interest status which can stop their sequence (not-interested),
 * mark them as interested, or reset to default status.
 *
 * Interest values:
 * - 1: Interested
 * - -1: Not Interested (stops sequence - no more emails)
 * - 0: Lead (default status)
 *
 * @param credentials - Instantly API key
 * @param params - Lead email, interest value, optional campaign ID and auto-interest setting
 * @param context - Execution context for logging
 * @returns Confirmation with success status and lead email
 */
export async function updateInterestStatus(
  credentials: InstantlyCredentials,
  params: UpdateInterestStatusParams,
  context?: ExecutionContext
): Promise<UpdateInterestStatusResult> {
  const { apiKey } = credentials
  const { lead_email, interest_value, campaign_id, disable_auto_interest } = params

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

  if (interest_value === undefined || interest_value === null) {
    throw new ToolingError('validation_error', 'Missing required parameter: interest_value', {
      integration: 'instantly',
      method: 'updateInterestStatus'
    })
  }

  if (![1, 0, -1].includes(interest_value)) {
    throw new ToolingError(
      'validation_error',
      'interest_value must be 1 (interested), 0 (default), or -1 (not-interested)',
      {
        integration: 'instantly',
        method: 'updateInterestStatus'
      }
    )
  }

  const updateUrl = `${INSTANTLY_API_BASE}/leads/update-interest-status`

  const requestBody: Record<string, unknown> = {
    lead_email,
    interest_value
  }

  if (campaign_id) {
    requestBody.campaign_id = campaign_id
  }

  if (disable_auto_interest !== undefined) {
    requestBody.disable_auto_interest = disable_auto_interest
  }

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Updating interest status: lead_email=${lead_email} interest_value=${interest_value} campaign_id=${campaign_id || 'all campaigns'} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

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

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[InstantlyAdapter] Interest status updated successfully: lead_email=${lead_email} interest_value=${interest_value} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  return {
    success: true,
    lead_email
  }
}
