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

interface AnymailfinderCredentials {
  apiKey: string
}

export interface FindCompanyEmailParams {
  domain: string
  company_name?: string
  email_type?: 'personal' | 'generic' | 'all'
}

export interface FindCompanyEmailResult {
  email_status: 'valid' | 'risky' | 'not_found' | 'blacklisted'
  emails: string[]
  valid_emails: string[]
}

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

/**
 * Find email addresses for a company via Anymailfinder
 *
 * Searches for company-level email addresses by domain or company name.
 * Returns all found emails plus the subset that passed validation.
 *
 * @param credentials - Anymailfinder API key
 * @param params - Domain or company name and optional email type filter
 * @param context - Execution context for logging
 * @returns Email status, all emails found, and valid emails only
 */
export async function findCompanyEmail(
  credentials: AnymailfinderCredentials,
  params: FindCompanyEmailParams,
  context?: ExecutionContext
): Promise<FindCompanyEmailResult> {
  const { apiKey } = credentials

  if (!params.domain && !params.company_name) {
    throw new Error('Either domain or company_name is required for findCompanyEmail')
  }

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] findCompanyEmail: organizationId=${context.organizationId} executionId=${context.executionId} domain=${params.domain} company_name=${params.company_name}`
    )
  }

  const response = await withRetry(async () => {
    const res = await fetch(`${ANYMAILFINDER_API_BASE}/find-email/company`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: apiKey
      },
      body: JSON.stringify(params)
    })

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

    return res.json()
  }, DEFAULT_RETRY_POLICY)

  if (context?.logger) {
    context.logger.info(
      `[AnymailfinderAdapter] findCompanyEmail complete: organizationId=${context.organizationId} email_status=${response.email_status} emailCount=${response.emails?.length ?? 0} validCount=${response.valid_emails?.length ?? 0}`
    )
  }

  return {
    email_status: response.email_status ?? 'not_found',
    emails: response.emails ?? [],
    valid_emails: response.valid_emails ?? []
  }
}
