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

interface TombaCredentials {
  apiKey: string
  apiSecret: string
}

export interface EmailVerifierParams {
  email: string
}

export interface EmailVerifierResult {
  email: string
  result: string
  status: string
  score: number
  mxRecords: boolean
  smtpServer: boolean
  smtpCheck: boolean
  acceptAll: boolean
  block: boolean
  gibberish: boolean
  disposable: boolean
  webmail: boolean
  regex: boolean
}

const TOMBA_API_BASE = 'https://api.tomba.io/v1'

/**
 * Verify an email address deliverability via Tomba
 *
 * Checks whether the given email address is valid and deliverable. Performs
 * MX record lookup, SMTP server check, and other validation signals.
 *
 * @param credentials - Tomba API key and secret
 * @param params - Email address to verify
 * @param context - Execution context for logging
 * @returns Detailed verification result including deliverability signals
 */
export async function emailVerifier(
  credentials: TombaCredentials,
  params: EmailVerifierParams,
  context?: ExecutionContext
): Promise<EmailVerifierResult> {
  const { apiKey, apiSecret } = credentials
  const { email } = params

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

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

  const url = new URL(`${TOMBA_API_BASE}/email-verifier`)
  url.searchParams.set('email', email)

  const response = await withRetry(async () => {
    const res = await fetch(url.toString(), {
      method: 'GET',
      headers: {
        'X-Tomba-Key': apiKey,
        'X-Tomba-Secret': apiSecret
      },
      signal: AbortSignal.timeout(60_000)
    })

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const data = (response.data?.email as Record<string, unknown>) ?? {}

  if (context?.logger) {
    context.logger.info(
      `[TombaAdapter] emailVerifier complete: email=${email} result=${data.result ?? ''} status=${data.status ?? ''} organizationId=${context.organizationId}`
    )
  }

  return {
    email: (data.email as string) ?? email,
    result: (data.result as string) ?? '',
    status: (data.status as string) ?? '',
    score: (data.score as number) ?? 0,
    mxRecords: (data.mx_records as boolean) ?? false,
    smtpServer: (data.smtp_server as boolean) ?? false,
    smtpCheck: (data.smtp_check as boolean) ?? false,
    acceptAll: (data.accept_all as boolean) ?? false,
    block: (data.block as boolean) ?? false,
    gibberish: (data.gibberish as boolean) ?? false,
    disposable: (data.disposable as boolean) ?? false,
    webmail: (data.webmail as boolean) ?? false,
    regex: (data.regex as boolean) ?? false
  }
}
