import type { Database } from '../../supabase/database.types'
import type {
  ActionRegistry,
  CredentialRequirement,
  RecordColumnConfig
} from '../../organization-model/domains/prospecting'
import type { DataMode, PipelineStage, ProcessingStageStatus } from './api-schemas'

// =============================================================================
// Supabase-Generated Types (Re-exported from database.types)
// =============================================================================

/** Raw database row type for acq_lists table */
export type AcqListRow = Database['public']['Tables']['acq_lists']['Row']
/** Insert type for acq_lists table */
export type AcqListInsert = Database['public']['Tables']['acq_lists']['Insert']

/** Raw database row type for acq_companies table */
export type AcqCompanyRow = Database['public']['Tables']['acq_companies']['Row']
/** Insert type for acq_companies table */
export type AcqCompanyInsert = Database['public']['Tables']['acq_companies']['Insert']

/** Raw database row type for acq_contacts table */
export type AcqContactRow = Database['public']['Tables']['acq_contacts']['Row']
/** Insert type for acq_contacts table */
export type AcqContactInsert = Database['public']['Tables']['acq_contacts']['Insert']

/** Raw database row type for acq_deals table */
export type AcqDealRow = Database['public']['Tables']['acq_deals']['Row']
/** Insert type for acq_deals table */
export type AcqDealInsert = Database['public']['Tables']['acq_deals']['Insert']

/** Raw database row type for acq_deal_tasks table */
export type AcqDealTaskRow = Database['public']['Tables']['acq_deal_tasks']['Row']
/** Insert type for acq_deal_tasks table */
export type AcqDealTaskInsert = Database['public']['Tables']['acq_deal_tasks']['Insert']

// =============================================================================
// Supporting Types
// =============================================================================

/**
 * Represents a web post from company website scraping.
 * Used for recent blog posts, news, or announcements.
 */
export interface WebPost {
  /** ISO date string of when the post was published */
  date: string
  /** Title of the web post */
  title: string
  /** Brief summary of the post content */
  summary: string
  /** AI-generated insight about the post's relevance */
  aiInsight?: string
}

export type LeadGenStageKey = string
export type LeadGenActionKey = ActionRegistry[number]['id']

export interface ProcessingStateEntry {
  status: ProcessingStageStatus
  data?: unknown
}

export type ProcessingState = Partial<Record<LeadGenStageKey, ProcessingStateEntry>>
export type CompanyProcessingState = ProcessingState
export type ContactProcessingState = ProcessingState
/** @deprecated Use `processingState`. Retained only as a compile-time/read-shape bridge for external tenants. */
export type LegacyPipelineStatus = unknown

/**
 * Enrichment data collected for a company from various sources.
 */
export interface CompanyEnrichmentData {
  googleMaps?: {
    placeId?: string
    totalScore?: number
    reviewsCount?: number
    address?: string
    phone?: string
    categoryName?: string
    googleMapsUrl?: string
    scrapedAt?: string
  }
  websiteCrawl?: {
    companyDescription?: string
    services?: string[]
    specialties?: string[]
    staff?: Array<{ name: string; title?: string; email?: string }>
    automationGaps?: string[]
    targetAudience?: string
    category?: string
    segment?: string
    recentWin?: string
    emailCount?: number
    pageCount?: number
    totalChars?: number
    crawledAt?: string
    extractedAt?: string
  }
  website?: {
    missionVision?: string
    uniqueAttributes?: string
    coreOfferings?: string
    targetAudience?: string
    companyValues?: string
    businessDescription?: string
    recentPosts?: Array<{ date?: string; title?: string; summary?: string; aiInsight?: string }>
  }
  tomba?: {
    waterfallEmail?: {
      email: string
      name?: string
      title?: string
      department?: string
    } | null
    genericEmail?: string | null
    totalFound?: number
    searchedAt?: string
  }
}

/**
 * Enrichment data collected for a contact from various sources.
 */
export interface ContactEnrichmentData {
  linkedin?: {
    summary?: string
    pastExperience?: string
    education?: string
    activity?: Array<{ date?: string; content?: string }>
  }
}

// =============================================================================
// Domain Types (camelCase transformations of database rows)
// =============================================================================

export type ListStatus = 'draft' | 'enriching' | 'launched' | 'closing' | 'archived'

export interface ScrapingConfig {
  source?: string
  query?: string
  filters?: Record<string, unknown>
  [key: string]: unknown
}

export interface IcpRubric {
  targetDescription?: string
  minReviewCount?: number
  minRating?: number
  excludeFranchises?: boolean
  customRules?: string
  qualificationRubricKey?: string | null
  [key: string]: unknown
}

export interface PipelineConfig {
  stages?: PipelineStage[]
  dataMode?: DataMode
}

export type BuildPlanSnapshotPrimaryEntity = 'company' | 'contact'
export type BuildPlanSnapshotOutput = 'company' | 'contact' | 'export'
export type BuildPlanSnapshotDependencyMode = 'per-record-eligibility'

export interface BuildPlanSnapshotStep {
  id: string
  label: string
  description?: string
  primaryEntity: BuildPlanSnapshotPrimaryEntity
  outputs: BuildPlanSnapshotOutput[]
  stageKey: string
  recordEntity?: BuildPlanSnapshotPrimaryEntity
  recordsStageKey?: string
  recordSourceStageKey?: string
  dependsOn?: string[]
  dependencyMode: BuildPlanSnapshotDependencyMode
  actionKey: string
  defaultBatchSize: number
  maxBatchSize: number
  recordColumns?: Partial<Record<BuildPlanSnapshotPrimaryEntity, RecordColumnConfig[]>>
  credentialRequirements?: CredentialRequirement[]
}

export interface BuildPlanSnapshot {
  templateId: string
  templateLabel: string
  steps: BuildPlanSnapshotStep[]
}

export interface AcqListMetadata extends Record<string, unknown> {
  buildPlanSnapshot?: BuildPlanSnapshot
}

export interface AcqList {
  id: string
  organizationId: string
  name: string
  description: string | null
  batchIds: string[]
  instantlyCampaignId: string | null
  status: ListStatus
  scrapingConfig: ScrapingConfig
  icp: IcpRubric
  pipelineConfig: PipelineConfig
  metadata: AcqListMetadata
  launchedAt: Date | null
  completedAt: Date | null
  createdAt: Date
}

/**
 * Company record in the acquisition database.
 * Contains enriched company data from various sources.
 * Transformed from AcqCompanyRow with camelCase properties.
 */
export interface AcqCompany {
  id: string
  organizationId: string
  name: string
  domain: string | null
  linkedinUrl: string | null
  website: string | null
  numEmployees: number | null
  foundedYear: number | null
  locationCity: string | null
  locationState: string | null
  category: string | null
  categoryPain: string | null
  segment: string | null
  processingState: CompanyProcessingState | null
  /** @deprecated Use `processingState`. This legacy DB column has been removed; responses return null. */
  pipelineStatus?: LegacyPipelineStatus | null
  enrichmentData: CompanyEnrichmentData | null
  source: string | null
  batchId: string | null
  status: 'active' | 'invalid'
  verticalResearch: string | null
  /** Track A: flat qualification score (null until a scoring rubric is defined). Added by W1 migration. */
  qualificationScore: number | null
  /** Track A: flat qualification signals jsonb preserving the result payload shape. Added by W1 migration. */
  qualificationSignals: Record<string, unknown> | null
  /** Track A: key identifying the rubric used for qualification. Added by W1 migration. */
  qualificationRubricKey: string | null
  createdAt: Date
  updatedAt: Date
}

/**
 * Contact record in the acquisition database.
 * Contains enriched contact data and personalization content.
 * Transformed from AcqContactRow with camelCase properties.
 */
export interface AcqContact {
  id: string
  organizationId: string
  companyId: string | null
  email: string
  emailValid: 'VALID' | 'INVALID' | 'RISKY' | 'UNKNOWN' | null
  firstName: string | null
  lastName: string | null
  linkedinUrl: string | null
  title: string | null
  headline: string | null
  filterReason: string | null
  openingLine: string | null
  source: string | null
  sourceId: string | null
  processingState: ContactProcessingState | null
  /** @deprecated Use `processingState`. This legacy DB column has been removed; responses return null. */
  pipelineStatus?: LegacyPipelineStatus | null
  enrichmentData: ContactEnrichmentData | null
  /** Attio Person record ID - set when contact responds and is added to CRM */
  attioPersonId: string | null
  batchId: string | null
  status: 'active' | 'invalid'
  createdAt: Date
  updatedAt: Date
}

// ─── Deal UI Types ───────────────────────────────────────────────────────────

export type DealStage = 'interested' | 'proposal' | 'closing' | 'closed_won' | 'closed_lost' | 'nurturing'

export type DealPriorityBucketKey = 'needs_response' | 'follow_up_due' | 'waiting' | 'stale' | 'closed_low'

export interface DealPriority {
  bucketKey: DealPriorityBucketKey
  rank: number
  label: string
  color: string
  reason: string
  latestActivityAt: string | null
  nextActionAt: string | null
}

export interface KanbanStageConfig {
  color: string // Mantine color token (e.g. 'blue', 'teal')
  label?: string // Optional display label override
}

export type KanbanBoardConfig = Partial<Record<DealStage, KanbanStageConfig>>

export interface DealContact {
  id: string
  first_name: string | null
  last_name: string | null
  email: string
  title: string | null
  headline: string | null
  linkedin_url: string | null
  processing_state: Record<string, unknown> | null
  enrichment_data: Record<string, unknown> | null
  company: {
    id: string
    name: string
    domain: string | null
    website: string | null
    linkedin_url: string | null
    segment: string | null
    category: string | null
    num_employees: number | null
  } | null
}

export interface DealFilters {
  stage?: DealStage
  search?: string
  limit?: number
  offset?: number
}

/** Deal list item with joined contact and company data */
export interface DealListItem extends AcqDealRow {
  priority: DealPriority
  ownership: 'us' | 'them' | null
  nextAction: string | null
  contact: DealContact | null
}

export type DealDetail = DealListItem

/** Task kind options for a deal task (human follow-up action type) */
export type AcqDealTaskKind = 'call' | 'email' | 'meeting' | 'other'

/**
 * A CRM to-do item attached to a deal representing a human follow-up action.
 * Transformed from AcqDealTaskRow with camelCase properties.
 */
export interface AcqDealTask {
  id: string
  organizationId: string
  dealId: string
  title: string
  description: string | null
  kind: AcqDealTaskKind
  dueAt: string | null
  assigneeUserId: string | null
  completedAt: string | null
  completedByUserId: string | null
  createdAt: string
  updatedAt: string
  createdByUserId: string | null
}

// ─── Progress / Telemetry Types ──────────────────────────────────────────────

/**
 * Live-scan aggregate telemetry for a single list, computed on demand from
 * the list junction tables and current contact deliverability state.
 * `stageCounts` are attempted counts from list-row processing_state.
 */
export interface ListTelemetry {
  listId: string
  totalCompanies: number
  totalContacts: number
  stageCounts: {
    populated: number
    extracted: number
    qualified: number
    discovered: number
    verified: number
    personalized: number
    uploaded: number
  }
  deliverability: {
    valid: number
    risky: number
    invalid: number
    unknown: number
    bounced: number
  }
  /** Reserved -- active workflow IDs associated with this list. */
  activeWorkflows?: string[]
}
