import type { BaseIntegrationAdapter } from '../../../base-integration-adapter'
import { ToolingError } from '../../../../types'
import type { ExecutionContext } from '../../../../../base/types'
import { sendReply } from './fetch/send-reply/index'
import { removeFromSubsequence } from './fetch/remove-from-subsequence/index'
import { getEmails } from './fetch/get-emails/index'
import { updateInterestStatus } from './fetch/update-interest-status/index'
import { addToCampaign } from './fetch/add-to-campaign/index'
import { listCampaigns } from './fetch/list-campaigns/index'
import type { ListCampaignsParams } from './fetch/list-campaigns/index'
import { getCampaign } from './fetch/get-campaign/index'
import type { GetCampaignParams } from './fetch/get-campaign/index'
import { updateCampaign } from './fetch/update-campaign/index'
import type { UpdateCampaignParams } from './fetch/update-campaign/index'
import { pauseCampaign } from './fetch/pause-campaign/index'
import type { PauseCampaignParams } from './fetch/pause-campaign/index'
import { activateCampaign } from './fetch/activate-campaign/index'
import type { ActivateCampaignParams } from './fetch/activate-campaign/index'
import { getCampaignAnalytics } from './fetch/get-campaign-analytics/index'
import type { GetCampaignAnalyticsParams } from './fetch/get-campaign-analytics/index'
import { getStepAnalytics } from './fetch/get-step-analytics/index'
import type { GetStepAnalyticsParams } from './fetch/get-step-analytics/index'
import { bulkAddLeads } from './fetch/bulk-add-leads/index'
import type { BulkAddLeadsParams } from './fetch/bulk-add-leads/index'
import { getAccountHealth } from './fetch/get-account-health/index'
import type { GetAccountHealthParams } from './fetch/get-account-health/index'
import { createInboxTest } from './fetch/create-inbox-test/index'
import type { CreateInboxTestParams } from './fetch/create-inbox-test/index'
import { createCampaign } from './fetch/create-campaign/index'
import type { CreateCampaignParams } from './fetch/create-campaign/index'
import { getDailyCampaignAnalytics } from './fetch/get-daily-campaign-analytics/index'
import type { GetDailyCampaignAnalyticsParams } from './fetch/get-daily-campaign-analytics/index'
import { listLeads } from './fetch/list-leads/index'
import type { ListLeadsParams } from './fetch/list-leads/index'
import { bulkDeleteLeads } from './fetch/bulk-delete-leads/index'
import type { BulkDeleteLeadsParams } from './fetch/bulk-delete-leads/index'
import { deleteCampaign } from './fetch/delete-campaign/index'
import type { DeleteCampaignParams } from './fetch/delete-campaign/index'
import { patchLead } from './fetch/patch-lead/index'
import type { PatchLeadParams } from './fetch/patch-lead/index'

interface InstantlyCredentials {
  apiKey: string
}

interface SendReplyParams {
  eaccount: string
  reply_to_uuid: string
  subject: string
  body: {
    text?: string
    html?: string
  }
  timestamp?: string
}

interface RemoveFromSubsequenceParams {
  lead_email: string
  campaign_id: string
}

interface GetEmailsParams {
  email_id?: string
  limit?: number
  offset?: number
}

interface UpdateInterestStatusParams {
  lead_email: string
  interest_value: number
  campaign_id?: string
  disable_auto_interest?: boolean
}

interface AddToCampaignLead {
  email: string
  first_name?: string
  last_name?: string
  company_name?: string
}

interface AddToCampaignParams {
  campaign_id: string
  leads: AddToCampaignLead[]
}

/**
 * Instantly.ai integration adapter
 *
 * Provides access to Instantly.ai email automation platform for cold email campaigns,
 * reply handling, and lead management.
 *
 * @example
 * const adapter = new InstantlyAdapter()
 * const result = await adapter.call(
 *   'sendReply',
 *   { eaccount: 'alex@elevasis.com', reply_to_uuid: '...', subject: 'Re: ...', body: { text: '...' } },
 *   { apiKey: 'instantly_api_...' },
 *   context
 * )
 */
export class InstantlyAdapter implements BaseIntegrationAdapter {
  readonly name = 'instantly'

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

    const creds = credentials as unknown as InstantlyCredentials

    // Route to method handler
    switch (method) {
      case 'sendReply':
        return sendReply(creds, params as SendReplyParams, context)
      case 'removeFromSubsequence':
        return removeFromSubsequence(creds, params as RemoveFromSubsequenceParams, context)
      case 'getEmails':
        return getEmails(creds, params as GetEmailsParams, context)
      case 'updateInterestStatus':
        return updateInterestStatus(creds, params as UpdateInterestStatusParams, context)
      case 'addToCampaign':
        return addToCampaign(creds, params as AddToCampaignParams, context)
      case 'listCampaigns':
        return listCampaigns(creds, params as ListCampaignsParams, context)
      case 'getCampaign':
        return getCampaign(creds, params as GetCampaignParams, context)
      case 'updateCampaign':
        return updateCampaign(creds, params as UpdateCampaignParams, context)
      case 'pauseCampaign':
        return pauseCampaign(creds, params as PauseCampaignParams, context)
      case 'activateCampaign':
        return activateCampaign(creds, params as ActivateCampaignParams, context)
      case 'getCampaignAnalytics':
        return getCampaignAnalytics(creds, params as GetCampaignAnalyticsParams, context)
      case 'getStepAnalytics':
        return getStepAnalytics(creds, params as GetStepAnalyticsParams, context)
      case 'bulkAddLeads':
        return bulkAddLeads(creds, params as BulkAddLeadsParams, context)
      case 'getAccountHealth':
        return getAccountHealth(creds, params as GetAccountHealthParams, context)
      case 'createInboxTest':
        return createInboxTest(creds, params as CreateInboxTestParams, context)
      case 'createCampaign':
        return createCampaign(creds, params as CreateCampaignParams, context)
      case 'getDailyCampaignAnalytics':
        return getDailyCampaignAnalytics(creds, params as GetDailyCampaignAnalyticsParams, context)
      case 'listLeads':
        return listLeads(creds, params as ListLeadsParams, context)
      case 'bulkDeleteLeads':
        return bulkDeleteLeads(creds, params as BulkDeleteLeadsParams, context)
      case 'deleteCampaign':
        return deleteCampaign(creds, params as DeleteCampaignParams, context)
      case 'patchLead':
        return patchLead(creds, params as PatchLeadParams, context)
      default:
        throw new ToolingError('method_not_found', `Unknown Instantly method: ${method}`, {
          integration: this.name,
          method,
          organizationId: context?.organizationId
        })
    }
  }

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