import type { BaseIntegrationAdapter } from '../../../base-integration-adapter'
import { ToolingError } from '../../../../types'
import type { ExecutionContext } from '../../../../../base/types'

import { emailFinder } from './fetch/email-finder/index'
import type { EmailFinderParams } from './fetch/email-finder/index'
import { domainSearch } from './fetch/domain-search/index'
import type { DomainSearchParams } from './fetch/domain-search/index'
import { emailVerifier } from './fetch/email-verifier/index'
import type { EmailVerifierParams } from './fetch/email-verifier/index'

interface TombaCredentials {
  apiKey: string
  apiSecret: string
}

/**
 * Tomba integration adapter
 *
 * Provides access to the Tomba email discovery API for finding and verifying
 * email addresses by company domain or person name. Uses dual-header
 * authentication (X-Tomba-Key + X-Tomba-Secret) on every request.
 *
 * @example
 * const adapter = new TombaAdapter()
 * const result = await adapter.call(
 *   'emailFinder',
 *   { domain: 'example.com', firstName: 'John', lastName: 'Doe' },
 *   { apiKey: 'ta_xxxx', apiSecret: 'ts_xxxx' },
 *   context
 * )
 */
export class TombaAdapter implements BaseIntegrationAdapter {
  readonly name = 'tomba'

  async call(
    method: string,
    params: unknown,
    credentials: Record<string, unknown>,
    context?: ExecutionContext
  ): Promise<unknown> {
    if (!this.validateCredentials(credentials)) {
      throw new ToolingError('credentials_invalid', 'Invalid Tomba credentials', {
        integration: this.name,
        organizationId: context?.organizationId
      })
    }

    const creds = credentials as unknown as TombaCredentials

    switch (method) {
      case 'emailFinder':
        return emailFinder(creds, params as EmailFinderParams, context)
      case 'domainSearch':
        return domainSearch(creds, params as DomainSearchParams, context)
      case 'emailVerifier':
        return emailVerifier(creds, params as EmailVerifierParams, context)
      default:
        throw new ToolingError('method_not_found', `Unknown Tomba method: ${method}`, {
          integration: this.name,
          method,
          organizationId: context?.organizationId
        })
    }
  }

  validateCredentials(credentials: Record<string, unknown>): boolean {
    const creds = credentials as unknown as TombaCredentials
    return (
      !!creds.apiKey &&
      typeof creds.apiKey === 'string' &&
      creds.apiKey.length > 0 &&
      !!creds.apiSecret &&
      typeof creds.apiSecret === 'string' &&
      creds.apiSecret.length > 0
    )
  }
}
