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

interface TombaCredentials {
  apiKey: string
  apiSecret: string
}

export interface EmailFinderParams {
  domain: string
  firstName: string
  lastName: string
}

export interface EmailFinderResult {
  email: string
  firstName: string
  lastName: string
  fullName: string
  position: string
  company: string
  country: string
  score: number
  verificationDate: string
  verificationStatus: string
  sources: Array<{
    uri: string
    extractedOn: string
    lastSeenOn: string
    stillOnPage: boolean
  }>
}

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

/**
 * Find a person's email address via Tomba
 *
 * Searches for a specific person's email by combining their first/last name
 * with a company domain. Returns enriched data including position, score, and
 * verification status.
 *
 * @param credentials - Tomba API key and secret
 * @param params - Domain, first name, and last name
 * @param context - Execution context for logging
 * @returns Email address with enrichment data and verification status
 */
export async function emailFinder(
  credentials: TombaCredentials,
  params: EmailFinderParams,
  context?: ExecutionContext
): Promise<EmailFinderResult> {
  const { apiKey, apiSecret } = credentials
  const { domain, firstName, lastName } = params

  if (!domain) {
    throw new Error('domain is required for emailFinder')
  }

  if (!firstName || !lastName) {
    throw new Error('firstName and lastName are required for emailFinder')
  }

  if (context?.logger) {
    context.logger.info(
      `[TombaAdapter] emailFinder: domain=${domain} firstName=${firstName} lastName=${lastName} organizationId=${context.organizationId} executionId=${context.executionId}`
    )
  }

  const url = new URL(`${TOMBA_API_BASE}/email-finder`)
  url.searchParams.set('domain', domain)
  url.searchParams.set('first_name', firstName)
  url.searchParams.set('last_name', lastName)

  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: 'emailFinder',
        organizationId: context?.organizationId
      })
    }

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  const data = response.data ?? {}

  if (context?.logger) {
    context.logger.info(
      `[TombaAdapter] emailFinder complete: email=${data.email ? '[found]' : '[not found]'} score=${data.score ?? 0} organizationId=${context.organizationId}`
    )
  }

  return {
    email: data.email ?? '',
    firstName: data.first_name ?? '',
    lastName: data.last_name ?? '',
    fullName: data.full_name ?? '',
    position: data.position ?? '',
    company: data.company ?? '',
    country: data.country ?? '',
    score: data.score ?? 0,
    verificationDate: data.verification?.date ?? '',
    verificationStatus: data.verification?.status ?? '',
    sources: (data.sources ?? []).map((s: Record<string, unknown>) => ({
      uri: s.uri ?? '',
      extractedOn: s.extracted_on ?? '',
      lastSeenOn: s.last_seen_on ?? '',
      stillOnPage: s.still_on_page ?? false
    }))
  }
}
