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

interface AnymailfinderCredentials {
  apiKey: string
}

export interface VerifyEmailParams {
  email: string
}

export interface VerifyEmailResult {
  email_status: 'valid' | 'risky' | 'not_found' | 'blacklisted'
}

const ANYMAILFINDER_API_BASE = 'https://api.anymailfinder.com/v5.1'

/**
 * Verify an email address via Anymailfinder
 *
 * Checks whether the given email address is valid, risky, not found, or
 * blacklisted. Costs 0.2 credits per valid result.
 *
 * @param credentials - Anymailfinder API key
 * @param params - Email address to verify
 * @param context - Execution context for logging
 * @returns Email status classification
 */
export async function verifyEmail(
  credentials: AnymailfinderCredentials,
  params: VerifyEmailParams,
  context?: ExecutionContext
): Promise<VerifyEmailResult> {
  const { apiKey } = credentials
  const { email } = params

  if (!email) {
    throw new ToolingError('validation_error', 'Missing required parameter: email', {
      integration: 'anymailfinder',
      method: 'verifyEmail'
    })
  }

  const verifyUrl = `${ANYMAILFINDER_API_BASE}/verify-email`

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] Verifying email: organizationId=${context.organizationId} executionId=${context.executionId} email=${email}`
    )
  }

  const response = await withRetry(async () => {
    const res = await fetch(verifyUrl, {
      method: 'POST',
      headers: {
        Authorization: apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email }),
      signal: AbortSignal.timeout(180_000)
    })

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] Email verification complete: organizationId=${context.organizationId} executionId=${context.executionId} email=${email} email_status=${response.email_status ?? 'not_found'}`
    )
  }

  return {
    email_status: response.email_status ?? 'not_found'
  }
}
