Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
65.1 KB
Raw Blame
class Account::ProviderImportAdapter
  SCHEDULED_MATCH_WINDOW_DAYS = 7

  attr_reader :account, :skipped_entries

  # @param account [Account] the account every import through this adapter lands on
  def initialize(account)
    @account = account
    @skipped_entries = []
  end

  # Resets skipped entries tracking (call at start of new sync batch)
  def reset_skipped_entries!
    @skipped_entries = []
  end

  # Imports a transaction from a provider
  #
  # @param external_id [String] Unique identifier from the provider (e.g., "plaid_12345", "simplefin_abc")
  # @param amount [BigDecimal, Numeric] Transaction amount
  # @param currency [String] Currency code (e.g., "USD")
  # @param date [Date, String] Transaction date
  # @param name [String] Transaction name/description
  # @param source [String] Provider name (e.g., "plaid", "simplefin")
  # @param category_id [Integer, nil] Optional category ID
  # @param merchant [Merchant, nil] Optional merchant object
  # @param notes [String, nil] Optional transaction notes/memo
  # @param pending_transaction_id [String, nil] Plaid's linking ID for pending→posted reconciliation
  # @param extra [Hash, nil] Optional provider-specific metadata to merge into transaction.extra
  # @param investment_activity_label [String, nil] Optional activity type label (e.g., "Buy", "Dividend")
  # @param allow_heuristic_matching [Boolean] Claim likely duplicates using amount/date matching
  # @param replace_extra_namespaces [Array<String>] Top-level `extra` keys the provider owns
  #   outright. Those branches are replaced rather than deep-merged, so a nested value the
  #   provider stops sending is actually removed instead of lingering.
  # @param name_extra_keys [Hash{String=>Array<String>}] Keys, per namespace, that `name`
  #   was built from. When a protected entry keeps its name, these keep their stored values
  #   too, so the name and the data it came from cannot drift apart.
  # @return [Entry] The created or updated entry
  def import_transaction(external_id:, amount:, currency:, date:, name:, source:, category_id: nil, kind: nil, merchant: nil, notes: nil, pending_transaction_id: nil, extra: nil, investment_activity_label: nil, allow_heuristic_matching: true, replace_extra_namespaces: [], name_extra_keys: {})
    raise ArgumentError, "external_id is required" if external_id.blank?
    raise ArgumentError, "source is required" if source.blank?

    Account.transaction do
      # Find or initialize by both external_id AND source
      # This allows multiple providers to sync same account with separate entries
      entry = account.entries.find_or_initialize_by(external_id: external_id, source: source) do |e|
        e.entryable = Transaction.new
      end

      # === TYPE COLLISION CHECK: Must happen before protection check ===
      # If entry exists but is a different type (e.g., Trade), that's an error.
      # This prevents external_id collisions across different entryable types.
      if entry.persisted? && !entry.entryable.is_a?(Transaction)
        raise ArgumentError, "Entry with external_id '#{external_id}' already exists with different entryable type: #{entry.entryable_type}"
      end

      # Determine early whether the incoming transaction is pending — needed by both
      # the protection check (pending→booked bypass) and the auto-claim path below.
      incoming_pending = extra.is_a?(Hash) && Transaction.pending_extra?(extra.with_indifferent_access)

      # An automatically excluded stale pending (see Entry.auto_exclude_stale_pending)
      # that the provider now delivers as booked under the same id becomes a normal
      # entry again. Entries the user excluded are never touched. An import_locked
      # entry that is not user_modified keeps its pending flag below, so it stays
      # excluded rather than being re-excluded on every sync.
      if entry.persisted? && !incoming_pending && entry.auto_excluded_pending? &&
          (entry.user_modified? || !entry.import_locked?)
        entry.update!(excluded: false) # also drops the mark (Entry callback)
      end

      # === PROTECTION CHECK: Skip entries that should not be overwritten ===
      # Check persisted Transaction entries for protection flags before making changes.
      # This prevents sync from overwriting user edits, CSV imports, or excluded entries.
      if entry.persisted?
        skip_reason = determine_skip_reason(entry)
        if skip_reason
          # Pending→booked bypass for user_modified entries: clear the stale pending flag
          # when the provider delivers a booked version of the same transaction.
          # Some ASPSPs (e.g. Revolut Italy via Enable Banking) reuse the same transaction_id
          # for pending and booked, so the entry is found by external_id rather than going
          # through the auto-claim path. Without this, a user who categorised a pending entry
          # (setting user_modified=true) would see the pending badge stuck forever.
          # Excluded and import_locked entries are intentionally left untouched.
          #
          # Load-bearing even though the namespace refresh below usually rewrites the
          # same branch: an entry that is both user_modified and import_locked reaches
          # here (determine_skip_reason reports user_modified first) but is excluded
          # from that refresh, so this is the only thing that clears its pending flag.
          if skip_reason == "user_modified" && !incoming_pending && entry.entryable.is_a?(Transaction)
            if entry.transaction.pending?
              entry.transaction.update!(extra: clear_pending_flags_from_extra(entry.transaction.extra))
            end
          end
          # Refresh the provider's own namespaces on a protected entry. Without this
          # a user-modified entry keeps whatever payload it was created with, and a
          # field the provider has since dropped shows in the drawer forever.
          #
          # Only the declared namespaces, never the whole payload. `extra` is not
          # uniformly provider-owned: Transaction#exchange_rate reads and writes
          # extra["exchange_rate"] at the top level, it is user-editable through the
          # transaction form, and WiseEntry::Processor supplies one too — so merging
          # the whole hash here would overwrite a rate the user typed and silently
          # change how their balance converts. replace_extra_namespaces defaults to
          # empty, so a provider that has not opted in changes nothing on this path.
          #
          # determine_skip_reason reports "user_modified" before it checks
          # import_locked?, so an entry carrying both flags arrives here. Import
          # ownership is the stronger claim, so those are left alone.
          if skip_reason == "user_modified" && !entry.import_locked?
            owned = extra.is_a?(Hash) ? extra.deep_stringify_keys.slice(*replace_extra_namespaces.map(&:to_s)) : nil
            owned = keep_name_sources(entry, owned, name_extra_keys)
            apply_provider_extra(entry, owned, replace_extra_namespaces)
          end

          record_skip(entry, skip_reason)
          return entry
        end
      end

      # If this is a new entry, check for potential duplicates from manual/CSV imports
      # This handles the case where a user manually created or CSV imported a transaction
      # before linking their account to a provider
      # Note: We don't pass name here to allow matching even when provider formats names differently
      if entry.new_record? && allow_heuristic_matching
        scheduled = find_scheduled_transaction(date: date, amount: amount, currency: currency)
        duplicate = find_duplicate_transaction(date: date, amount: amount, currency: currency) unless scheduled

        if scheduled
          # A bill or paycheck the user entered ahead of time has now been
          # booked. Claim it even when the user's edits protect it: the
          # enrichment below still respects their locks (name, category, notes),
          # but the provider's date and pending state must apply -- otherwise
          # the entry stays on its expected day, and a pending claim would never
          # be recognized when the booked version arrives under a new id.
          entry = scheduled
          entry.assign_attributes(external_id: external_id, source: source, date: date)
        elsif duplicate
          # Check if duplicate is protected - if so, link but don't modify
          if duplicate.protected_from_sync?
            duplicate.update!(external_id: external_id, source: source)
            record_skip(duplicate, determine_skip_reason(duplicate) || "protected")
            return duplicate
          end

          # "Claim" the unprotected duplicate by updating its external_id and source
          # This prevents future duplicate checks from matching it again
          entry = duplicate
          entry.assign_attributes(external_id: external_id, source: source)
        end
      end

      if entry.new_record? && !incoming_pending
        pending_match = nil

        # PRIORITY 1: Use Plaid's pending_transaction_id if provided (most reliable)
        # Plaid explicitly links pending→posted with this ID - no guessing required
        if pending_transaction_id.present?
          pending_match = account.entries.find_by(external_id: pending_transaction_id, source: source)
          if pending_match
            Rails.logger.info("Reconciling pending→posted via Plaid pending_transaction_id: claiming entry #{pending_match.id} (#{pending_match.name}) with new external_id #{external_id}")
          end
        end

        # PRIORITY 2: Fallback to EXACT amount match (for SimpleFIN and providers without linking IDs)
        # Only searches backward in time - pending date must be <= posted date
        if pending_match.nil? && allow_heuristic_matching
          pending_match = find_pending_transaction(date: date, amount: amount, currency: currency, source: source)
          if pending_match
            Rails.logger.info("Reconciling pending→posted via exact amount match: claiming entry #{pending_match.id} (#{pending_match.name}) with new external_id #{external_id}")
          end
        end

        if pending_match
          old_pending_external_id = pending_match.external_id
          pending_entry_date      = pending_match.date
          entry = pending_match
          entry.assign_attributes(external_id: external_id)

          # Clear the pending flag so this entry no longer shows as pending after being claimed
          # by a booked transaction. Also record the old external_id so the sync engine can
          # exclude it from re-import (preventing the old pending from being recreated on the
          # next sync when the stored raw payload still contains the pending transaction data).
          if entry.entryable.is_a?(Transaction)
            ex = clear_pending_flags_from_extra(entry.transaction.extra)
            if old_pending_external_id.present?
              existing_claims = Array.wrap(ex["auto_claimed_pending_ids"])
              ex["auto_claimed_pending_ids"] = (existing_claims + [ old_pending_external_id ]).uniq
            end
            entry.transaction.extra = ex
          end
        end
      end

      # Pending→booked for same-external-id providers (non-protected path).
      # For ASPSPs like Revolut Italy that reuse the same transaction_id for pending and
      # booked, the auto-claim path above is skipped (entry.persisted? from the start).
      # If extra is nil (no FX, no MCC) the deep-merge block later is skipped too, so we
      # must clear the stale pending flag here before the final save.
      # (The auto-claim path already clears it in-memory, so this is a no-op there.)
      if !incoming_pending && entry.entryable.is_a?(Transaction)
        if entry.transaction.pending?
          entry.transaction.extra = clear_pending_flags_from_extra(entry.transaction.extra)
        end
      end

      # Track if this is a new posted transaction (for fuzzy suggestion after save)
      is_new_posted = entry.new_record? && !incoming_pending

      # Preserve the original pending date across all syncs:
      # - First claim: pending_entry_date is captured from the pending match above
      # - Subsequent syncs: entry already exists (no pending_match found), so check
      #   auto_claimed_pending_ids which signals it was previously auto-claimed and
      #   keep entry.date (the pending date stored on first claim) unchanged
      effective_date = if pending_entry_date
        pending_entry_date
      elsif !entry.new_record? &&
            entry.entryable.is_a?(Transaction) &&
            entry.transaction.extra&.key?("auto_claimed_pending_ids")
        entry.date
      else
        date
      end

      # A date or amount the user changed without marking the entry user_modified
      # (an API PATCH, for example) is still locked by lock_saved_attributes!.
      # Respect that lock the way enrich_attribute does for name and category.
      # Amount and currency only make sense together, so a lock on either keeps both.
      financial_attributes = { amount: amount, currency: currency, date: effective_date }
      if entry.persisted?
        financial_attributes.delete(:date) if entry.locked?(:date)
        financial_attributes.except!(:amount, :currency) if entry.locked?(:amount) || entry.locked?(:currency)
      end
      entry.assign_attributes(financial_attributes)

      # Use enrichment pattern to respect user overrides
      entry.enrich_attribute(:name, name, source: source)

      # Enrich transaction-specific attributes
      if category_id
        entry.transaction.enrich_attribute(:category_id, category_id, source: source)
      end

      if merchant
        entry.transaction.enrich_attribute(:merchant_id, merchant.id, source: source)
      end

      if notes.present? && entry.respond_to?(:enrich_attribute)
        entry.enrich_attribute(:notes, notes, source: source)
      end

      # Persist extra provider metadata on the transaction (non-enriched; always merged)
      apply_provider_extra(entry, extra, replace_extra_namespaces)

      # Auto-detect investment activity labels for investment accounts
      detected_label = investment_activity_label
      if account.investment? && detected_label.nil? && entry.entryable.is_a?(Transaction)
        detected_label = detect_activity_label(name, entry.amount)
      end

      # Determine the transaction kind. Activity-label and account-type classification
      # take precedence; an explicit kind supplied by the provider is used as a fallback
      # for the standard case. A provider such as Up flags internal transfers and
      # round-ups (via relationships.transferAccount) and passes funds_movement, but a
      # repayment imported onto a linked Loan/CreditCard account must stay
      # loan_payment/cc_payment (a budgeted expense) rather than being reclassified, so
      # the account-type branches below win over the provider hint.
      auto_kind = nil
      auto_category = nil
      if Transaction::INTERNAL_MOVEMENT_LABELS.include?(detected_label)
        auto_kind = "funds_movement"
      elsif detected_label == "Contribution" && (account.investment? || account.crypto?)
        # Some providers (SnapTrade for Wealthsimple cash accounts) label every
        # deposit on a bank account CONTRIBUTION. There it is salary or another
        # inflow, not money moving into an investment, so it keeps its own kind.
        auto_kind = "investment_contribution"
        auto_category = account.family.investment_contributions_category
      elsif account.accountable_type == "Loan" && entry.amount.negative?
        auto_kind = "loan_payment"
      end
      auto_kind ||= kind.presence

      # Set investment activity label, kind, and category if detected
      if entry.entryable.is_a?(Transaction)
        if detected_label.present? && entry.transaction.investment_activity_label.blank?
          entry.transaction.assign_attributes(investment_activity_label: detected_label)
        end

        # A leg that is already matched to a Transfer takes its kind from the
        # transfer, not from this row. Re-classifying it here, e.g. a negative
        # amount on a Loan turning the matched inflow back into loan_payment,
        # makes budgets and reports count the same payment as an expense on
        # both legs. Deriving it from the transfer also repairs legs an earlier
        # sync already overwrote. An unconfirmed auto-match gets its kinds only
        # in Transfer#confirm!, so until then the leg keeps its own kind.
        if auto_kind.present?
          transfer = matched_transfer_for(entry)
          transfer = nil if transfer&.pending?
          entry.transaction.assign_attributes(kind: transfer ? transfer.kind_for_leg(entry.transaction) : auto_kind)
        end

        # Only while the leg is a contribution: a matched transfer can make it
        # a plain transfer above, which carries no category.
        if auto_category.present? && entry.transaction.category_id.blank? && entry.transaction.kind == "investment_contribution"
          entry.transaction.assign_attributes(category: auto_category)
        end
      end

      entry.save!
      entry.transaction.save! if entry.transaction.changed?

      # Auto-resolve any open Goal pledges on this account whose tolerance
      # window matches the posted transaction. Idempotent via the partial-unique
      # index on transactions.extra->'goal'->>'pledge_id'.
      #
      # Short-circuit when the account isn't linked to any goal: a 2k-row
      # historical Plaid import on an unlinked account otherwise pays one
      # SELECT per row. goal_accounts membership is stable across a sync
      # batch, so memoize once per adapter instance (one query per account
      # synced, not per transaction).
      if !incoming_pending && account_linked_to_any_goal?
        GoalPledge::Reconciler.new(entry).run
      end

      # AFTER save: For NEW posted transactions, check for fuzzy matches to SUGGEST (not auto-claim)
      # This handles tip adjustments where auto-matching is too risky
      if is_new_posted && allow_heuristic_matching
        # PRIORITY 1: Try medium-confidence fuzzy match (≤30% amount difference)
        fuzzy_suggestion = find_pending_transaction_fuzzy(
          date: date,
          amount: amount,
          currency: currency,
          source: source,
          merchant_id: merchant&.id,
          name: name
        )
        if fuzzy_suggestion
          # Store suggestion on the PENDING entry for user to review
          begin
            store_duplicate_suggestion(
              pending_entry: fuzzy_suggestion,
              posted_entry: entry,
              reason: "fuzzy_amount_match",
              posted_amount: amount,
              confidence: "medium"
            )
            Rails.logger.info("Suggested potential duplicate (medium confidence): pending entry #{fuzzy_suggestion.id} (#{fuzzy_suggestion.name}, #{fuzzy_suggestion.amount}) may match posted #{entry.name} (#{amount})")
          rescue ActiveRecord::RecordInvalid => e
            Rails.logger.warn("Failed to store duplicate suggestion for entry #{fuzzy_suggestion.id}: #{e.message}")
          end
        else
          # PRIORITY 2: Try low-confidence match (>30% to 100% difference - big tips)
          low_confidence_suggestion = find_pending_transaction_low_confidence(
            date: date,
            amount: amount,
            currency: currency,
            source: source,
            merchant_id: merchant&.id,
            name: name
          )
          if low_confidence_suggestion
            begin
              store_duplicate_suggestion(
                pending_entry: low_confidence_suggestion,
                posted_entry: entry,
                reason: "low_confidence_match",
                posted_amount: amount,
                confidence: "low"
              )
              Rails.logger.info("Suggested potential duplicate (low confidence): pending entry #{low_confidence_suggestion.id} (#{low_confidence_suggestion.name}, #{low_confidence_suggestion.amount}) may match posted #{entry.name} (#{amount})")
            rescue ActiveRecord::RecordInvalid => e
              Rails.logger.warn("Failed to store duplicate suggestion for entry #{low_confidence_suggestion.id}: #{e.message}")
            end
          end
        end
      end

      entry
    end
  end

  # Finds or creates a merchant from provider data
  #
  # @param provider_merchant_id [String] Provider's merchant ID
  # @param name [String] Merchant name
  # @param source [String] Provider name (e.g., "plaid", "simplefin")
  # @param website_url [String, nil] Optional merchant website
  # @param logo_url [String, nil] Optional merchant logo URL
  # @return [ProviderMerchant, nil] The merchant object or nil if data is insufficient
  def find_or_create_merchant(provider_merchant_id:, name:, source:, website_url: nil, logo_url: nil)
    return nil unless provider_merchant_id.present? && name.present?

    # First try to find by provider_merchant_id (stable identifier derived from normalized name)
    # This handles case variations in merchant names (e.g., "ACME Corp" vs "Acme Corp")
    merchant = ProviderMerchant.find_by(provider_merchant_id: provider_merchant_id, source: source)

    # If not found by provider_merchant_id, try by exact name match (backwards compatibility)
    merchant ||= ProviderMerchant.find_by(source: source, name: name)

    if merchant
      # Update logo if provided and merchant doesn't have one (or has a different one)
      # Best-effort: don't fail transaction import if logo update fails
      if logo_url.present? && merchant.logo_url != logo_url
        begin
          merchant.update!(logo_url: logo_url)
        rescue StandardError => e
          Rails.logger.warn("Failed to update merchant logo: merchant_id=#{merchant.id} logo_url=#{logo_url} error=#{e.message}")
        end
      end
      return merchant
    end

    # Create new merchant
    begin
      merchant = ProviderMerchant.create!(
        source: source,
        name: name,
        provider_merchant_id: provider_merchant_id,
        website_url: website_url,
        logo_url: logo_url
      )
    rescue ActiveRecord::RecordNotUnique
      # Race condition - another process created the record
      merchant = ProviderMerchant.find_by(provider_merchant_id: provider_merchant_id, source: source) ||
                 ProviderMerchant.find_by(source: source, name: name)
    end

    merchant
  end

  # Updates account balance from provider data
  #
  # @param balance [BigDecimal, Numeric] Total balance
  # @param cash_balance [BigDecimal, Numeric] Cash balance (for investment accounts)
  # @param source [String] Provider name (for logging/debugging)
  def update_balance(balance:, cash_balance: nil, source: nil)
    account.update!(
      balance: balance,
      cash_balance: cash_balance || balance
    )
  end

  # Imports or updates a holding (investment position) from a provider
  #
  # @param security [Security] The security object
  # @param quantity [BigDecimal, Numeric] Number of shares/units
  # @param amount [BigDecimal, Numeric] Total value in account currency
  # @param currency [String] Currency code
  # @param date [Date, String] Holding date
  # @param price [BigDecimal, Numeric, nil] Price per share (optional)
  # @param cost_basis [BigDecimal, Numeric, nil] Cost basis (optional)
  # @param external_id [String, nil] Provider's unique ID (optional, for deduplication)
  # @param source [String] Provider name
  # @param account_provider_id [String, nil] The AccountProvider ID that owns this holding (optional)
  # @param delete_future_holdings [Boolean] Whether to delete holdings after this date (default: false)
  # @return [Holding] The created or updated holding
  def import_holding(security:, quantity:, amount:, currency:, date:, price: nil, cost_basis: nil, external_id: nil, source:, account_provider_id: nil, delete_future_holdings: false)
    raise ArgumentError, "security is required" if security.nil?
    raise ArgumentError, "source is required" if source.blank?

    Account.transaction do
      # Two strategies for finding/creating holdings:
      # 1. By external_id (SimpleFin approach) - tracks each holding uniquely
      # 2. By security+date+currency (Plaid approach) - overwrites holdings for same security/date
      holding = nil

      if external_id.present?
        # Preferred path: match by provider's external_id
        holding = account.holdings.find_by(external_id: external_id)

        unless holding
          # Fallback path 1a: match by provider_security (for remapped holdings)
          # This allows re-matching a holding that was remapped to a different security
          # Scope by account_provider_id to avoid cross-provider overwrites
          fallback_1a_attrs = {
            provider_security: security,
            date: date,
            currency: currency
          }
          fallback_1a_attrs[:account_provider_id] = account_provider_id if account_provider_id.present?
          holding = account.holdings.find_by(fallback_1a_attrs)

          # Fallback path 1b: match by provider_security ticker (for remapped holdings when
          # Security::Resolver returns a different security instance for the same ticker)
          # Scope by account_provider_id to avoid cross-provider overwrites
          # Skip if ticker is blank to avoid matching NULL tickers
          # External ids are unique per account, so a same-day row with an id of
          # its own is another of the provider's positions, not this one under
          # another security: only a row stored without an id (nil, or blank as
          # the branch below stores a blank one) can match.
          # The same ticker on another exchange can be a different company, so a
          # known exchange has to agree with this one's, the same listing coming
          # before one stored without an exchange. A row matches only when no
          # other candidate is as good a match: two rows on the same exchange,
          # or two without one, leave the holding unmatched.
          unless holding || security.ticker.blank?
            scope = account.holdings
              .joins("INNER JOIN securities AS ps ON ps.id = holdings.provider_security_id")
              .where(date: date, currency: currency, external_id: [ nil, "" ])
              .where("ps.ticker = ?", security.ticker)
            venues = Security.exchange_operating_mic_lookup_values(security.exchange_operating_mic)
            scope = scope.where("COALESCE(ps.exchange_operating_mic, '') = '' OR UPPER(ps.exchange_operating_mic) IN (?)", venues) if venues.any?
            scope = scope.where(account_provider_id: account_provider_id) if account_provider_id.present?
            first, second = scope.select("holdings.*, COALESCE(ps.exchange_operating_mic, '') AS provider_mic")
                                 .order(Arel.sql("COALESCE(ps.exchange_operating_mic, '') = ''"), :id).limit(2).to_a
            holding = first if first && (second.nil? || (venues.any? && first.provider_mic.present? && second.provider_mic.blank?))
          end

          # Fallback path 2: match by (security, date, currency) — and when provided,
          # also scope by account_provider_id to avoid cross‑provider claiming.
          # This keeps behavior symmetric with deletion logic below which filters
          # by account_provider_id when present.
          unless holding
            find_by_attrs = {
              security: security,
              date: date,
              currency: currency
            }
            if account_provider_id.present?
              find_by_attrs[:account_provider_id] = account_provider_id
            end

            holding = account.holdings.find_by(find_by_attrs)
          end
        end

        # Built outside account.holdings, as below: a record built there joins
        # the account's holdings unsaved, and an import that fails after that
        # (a collision, a validation) would leave the account unable to save.
        holding ||= Holding.new(
          account: account,
          security: security,
          date: date,
          currency: currency,
          account_provider_id: account_provider_id
        )
      else
        # A remapped row sits on the user's chosen security, so a lookup by the
        # incoming security alone misses it and the save hits the unique index.
        # Match it by provider_security first, as fallback 1a does, scoped by
        # account_provider_id so another provider's row is not claimed.
        remapped_attrs = { provider_security: security, date: date, currency: currency }
        remapped_attrs[:account_provider_id] = account_provider_id if account_provider_id.present?
        holding = account.holdings.find_by(remapped_attrs)

        holding ||= account.holdings.find_by(security: security, date: date, currency: currency) ||
          Holding.new(account: account, security: security, date: date, currency: currency)
      end

      # Early cross-provider composite-key conflict guard: avoid attempting a write
      # that would violate a unique index on (account_id, security_id, date, currency).
      if external_id.present?
        existing_composite = account.holdings.find_by(
          security: security,
          date: date,
          currency: currency
        )

        if existing_composite &&
           account_provider_id.present? &&
           existing_composite.account_provider_id.present? &&
           existing_composite.account_provider_id != account_provider_id
          Rails.logger.warn(
            "ProviderImportAdapter: cross-provider holding collision for account=#{account.id} security=#{security.id} date=#{date} currency=#{currency}; returning existing id=#{existing_composite.id}"
          )
          return existing_composite
        end
      end

      # A new row for a later day starts without the user's corrections, which
      # live on the earlier day's row. Carry them forward from that row.
      carried = holding.new_record? ? previous_holding_for(security: security, currency: currency, date: date, account_provider_id: account_provider_id) : nil

      # Reconcile cost_basis to respect priority hierarchy
      reconciled = Holding::CostBasisReconciler.reconcile(
        existing_holding: holding.persisted? ? holding : nil,
        incoming_cost_basis: cost_basis,
        incoming_source: "provider"
      )

      # Build base attributes
      attributes = {
        date: date,
        currency: currency,
        qty: quantity,
        price: price,
        amount: amount,
        account_provider_id: account_provider_id,
        external_id: external_id
      }

      corrections = corrections_from(carried, provider_security_id: security.id)
      attributes.merge!(corrections)

      # Only update security if not locked by user
      if !corrections.key?(:security) && (holding.new_record? || holding.security_replaceable_by_provider?)
        attributes[:security] = security
        # Track the provider's original security so reset_security_to_provider! works
        # Only set if not already set (preserves original if user remapped then unlocked)
        attributes[:provider_security_id] = security.id if holding.provider_security_id.blank?
      end

      # Only update cost_basis if reconciliation says to
      if !corrections.key?(:cost_basis) && reconciled[:should_update]
        attributes[:cost_basis] = reconciled[:cost_basis]
        attributes[:cost_basis_source] = reconciled[:cost_basis_source]
      end

      holding.assign_attributes(attributes)

      begin
        Holding.transaction(requires_new: true) do
          holding.save!
        end
      rescue ActiveRecord::RecordNotUnique => e
        # Handle unique index collisions on (account_id, security_id, date, currency)
        # that can occur when another provider (or concurrent import) already
        # created a row for this composite key. Use the existing row and keep
        # the outer transaction valid by isolating the error in a savepoint.
        existing = account.holdings.find_by(
          security: security,
          date: date,
          currency: currency
        )

        if existing
          # If an existing row belongs to a different provider, do NOT claim it.
          # Keep cross-provider isolation symmetrical with deletion logic.
          if account_provider_id.present? && existing.account_provider_id.present? && existing.account_provider_id != account_provider_id
            Rails.logger.warn(
              "ProviderImportAdapter: cross-provider holding collision for account=#{account.id} security=#{security.id} date=#{date} currency=#{currency}; returning existing id=#{existing.id}"
            )
            holding = existing
          else
            # Same provider (or unowned). Apply latest snapshot and attach external_id for idempotency.
            updates = {
              qty: quantity,
              price: price,
              amount: amount
            }

            # Reconcile cost_basis to respect priority hierarchy
            collision_reconciled = Holding::CostBasisReconciler.reconcile(
              existing_holding: existing,
              incoming_cost_basis: cost_basis,
              incoming_source: "provider"
            )

            if collision_reconciled[:should_update]
              updates[:cost_basis] = collision_reconciled[:cost_basis]
              updates[:cost_basis_source] = collision_reconciled[:cost_basis_source]
            end

            # Adopt the row to this provider if it's currently unowned
            if account_provider_id.present? && existing.account_provider_id.nil?
              updates[:account_provider_id] = account_provider_id
            end

            # Attach external_id if provided and missing
            if external_id.present? && existing.external_id.blank?
              updates[:external_id] = external_id
            end

            begin
              # Use update_columns to avoid validations and keep this collision handler best-effort.
              existing.update_columns(updates.compact)
            rescue => _
              # Best-effort only; avoid raising in collision handler
            end

            holding = existing
          end
        else
          # Could not find an existing row; re-raise original error
          raise e
        end
      end

      # Optionally delete future holdings for this security (Plaid behavior)
      # Only delete if ALL providers allow deletion (cross-provider check)
      if delete_future_holdings
        unless account.can_delete_holdings?
          Rails.logger.warn(
            "Skipping future holdings deletion for account #{account.id} " \
            "because not all providers allow deletion"
          )
          return holding
        end

        # Build base query for future holdings
        future_holdings_query = account.holdings
          .where(security: security)
          .where("date > ?", date)

        # If account_provider_id is provided, only delete holdings from this provider
        # This prevents deleting positions imported by other providers
        if account_provider_id.present?
          future_holdings_query = future_holdings_query.where(account_provider_id: account_provider_id)
        end

        future_holdings_query.destroy_all
      end

      holding
    end
  end

  # Imports a trade (investment transaction) from a provider
  #
  # @param security [Security] The security object
  # @param quantity [BigDecimal, Numeric] Number of shares (negative for sells, positive for buys)
  # @param price [BigDecimal, Numeric] Price per share
  # @param amount [BigDecimal, Numeric] Total cash impact of the trade, fee included
  # @param currency [String] Currency code
  # @param date [Date, String] Trade date
  # @param name [String, nil] Optional custom name for the trade
  # @param external_id [String, nil] Provider's unique ID (optional, for deduplication)
  # @param source [String] Provider name
  # @param activity_label [String, nil] Investment activity label (e.g., "Buy", "Sell", "Reinvestment")
  # @param exchange_rate [BigDecimal, Numeric, nil] Optional provider-supplied FX rate into the account currency
  # @param fee [BigDecimal, Numeric, nil] Optional provider-reported transaction fee, already included in `amount`
  # @return [Entry] The created entry with trade
  def import_trade(security:, quantity:, price:, amount:, currency:, date:, name: nil, external_id: nil, source:, activity_label: nil, exchange_rate: nil, fee: nil)
    raise ArgumentError, "security is required" if security.nil?
    raise ArgumentError, "source is required" if source.blank?

    Account.transaction do
      # Generate name if not provided
      trade_name = if name.present?
        name
      else
        trade_type = quantity.negative? ? "sell" : "buy"
        Trade.build_name(trade_type, quantity, security.ticker)
      end

      # Use find_or_initialize_by with external_id if provided, otherwise create new
      entry = if external_id.present?
        # Find or initialize by both external_id AND source
        # This allows multiple providers to sync same account with separate entries
        account.entries.find_or_initialize_by(external_id: external_id, source: source) do |e|
          e.entryable = Trade.new
        end
      else
        account.entries.new(
          entryable: Trade.new,
          source: source
        )
      end

      # Validate entryable type matches to prevent external_id collisions
      if entry.persisted? && !entry.entryable.is_a?(Trade)
        raise ArgumentError, "Entry with external_id '#{external_id}' already exists with different entryable type: #{entry.entryable_type}"
      end

      # Always update Trade attributes (works for both new and existing records)
      trade_attributes = {
        security: security,
        qty: quantity,
        price: price,
        currency: currency,
        investment_activity_label: activity_label || (quantity > 0 ? "Buy" : "Sell")
      }
      trade_attributes[:exchange_rate] = exchange_rate unless exchange_rate.nil?
      trade_attributes[:fee] = fee unless fee.nil?

      entry.entryable.assign_attributes(trade_attributes)

      entry.assign_attributes(
        date: date,
        amount: amount,
        currency: currency,
        name: trade_name
      )

      entry.save!

      # Coins arriving in a wallet are its deposits (GoalPledge.deposit_trade?).
      # After commit, because a wallet writes the trade inside its own
      # transaction. A re-imported trade is skipped by the reconciler once
      # stamped.
      if GoalPledge.deposit_trade?(entry) && account_linked_to_any_goal?
        GoalPledge::Reconciler.run_after_commit(entry)
      end

      entry
    end
  end

  # Updates accountable-specific attributes (e.g., credit card details, loan details)
  #
  # @param attributes [Hash] Hash of attributes to update on the accountable
  # @param source [String] Provider name (for logging/debugging)
  # @return [Boolean] Whether the update was successful
  def update_accountable_attributes(attributes:, source:)
    return false unless account.accountable.present?
    return false if attributes.blank?

    # Filter out nil values and only update attributes that exist on the accountable
    valid_attributes = attributes.compact.select do |key, _|
      account.accountable.respond_to?("#{key}=")
    end

    return false if valid_attributes.empty?

    account.accountable.update!(valid_attributes)
    true
  rescue => e
    Rails.logger.error("Failed to update #{account.accountable_type} attributes from #{source}: #{e.message}")
    false
  end

  # Finds a potential duplicate transaction from manual entry or CSV import
  # Matches on date, amount, currency, and optionally name
  # Only matches transactions without external_id (manual/CSV imported)
  #
  # @param date [Date, String] Transaction date
  # @param amount [BigDecimal, Numeric] Transaction amount
  # @param currency [String] Currency code
  # @param name [String, nil] Optional transaction name for more accurate matching
  # @param exclude_entry_ids [Set, Array, nil] Entry IDs to exclude from the search (e.g., already claimed entries)
  # @return [Entry, nil] The duplicate entry or nil if not found
  # @param date_window [Integer] days either side of `date` to consider. Defaults
  #   to 0 (exact date), which is what provider sync wants. Statement imports
  #   pass a small window, because a statement's posting date routinely differs
  #   from the date a provider recorded for the same transaction.
  # @param include_provider_entries [Boolean] when false (the default) only
  #   manual and CSV-imported entries are considered, which is correct for
  #   provider sync: a provider must not claim another provider's entry. A
  #   statement import passes true, because the whole question it is asking is
  #   whether this transaction already arrived via sync.
  def find_duplicate_transaction(date:, amount:, currency:, name: nil, exclude_entry_ids: nil, date_window: 0, include_provider_entries: false)
    # Convert date to Date object if it's a string
    date = Date.parse(date.to_s) unless date.is_a?(Date)

    # Look for entries on the same account with:
    # 1. Same date (or within date_window of it)
    # 2. Same amount (exact match)
    # 3. Same currency
    # 4. No external_id (manual/CSV imported transactions), unless the caller
    #    opted into provider-sourced entries too
    # 5. Entry type is Transaction (not Trade or Valuation)
    # 6. Optionally same name (if name parameter is provided)
    # 7. Not in the excluded IDs list (if provided)
    # 8. Not a part of a split entry: a person's share of another movement,
    #    never a copy of the incoming one
    query = account.entries
                   .where(entryable_type: "Transaction")
                   .where(amount: amount)
                   .where(currency: currency)
                   .where(parent_entry_id: nil)

    query = if date_window.to_i.zero?
      query.where(date: date)
    else
      query.where(date: (date - date_window.days)..(date + date_window.days))
    end

    query = query.where(external_id: nil) unless include_provider_entries

    # Add name filter if provided
    query = query.where(name: name) if name.present?

    # Exclude already claimed entries if provided
    query = query.where.not(id: exclude_entry_ids) if exclude_entry_ids.present?

    candidates = query.order(created_at: :asc)

    # Exact-date search keeps the original oldest-first behaviour.
    return candidates.first if date_window.to_i.zero?

    # A windowed search prefers the closest date, falling back to oldest-created
    # on a tie. Done in Ruby because the candidate set is already narrowed to one
    # account, one amount and one currency within a few days -- a handful of rows.
    candidates.to_a.min_by { |entry| [ (entry.date - date).abs, entry.created_at ] }
  end

  # Finds a manual transaction the user entered ahead of its date -- an
  # upcoming bill or paycheck (see Entry#scheduled?) -- that the provider has
  # now booked. Providers rarely book on exactly the expected day, so this
  # allows a few days either side of it, but still requires the exact amount
  # and currency. Only entries created before their own date qualify, so
  # ordinary manual entries keep find_duplicate_transaction's exact-date rule.
  #
  # @return [Entry, nil] the closest-dated match, or nil
  def find_scheduled_transaction(date:, amount:, currency:, date_window: SCHEDULED_MATCH_WINDOW_DAYS)
    date = Date.parse(date.to_s) unless date.is_a?(Date)

    account.entries
      .where(entryable_type: "Transaction", external_id: nil, amount: amount, currency: currency)
      .where(date: (date - date_window.days)..(date + date_window.days))
      .where("entries.created_at < entries.date")
      .to_a
      .min_by { |entry| [ (entry.date - date).abs, entry.created_at ] }
  end

  # Finds a pending transaction that likely matches a newly posted transaction
  # Used to reconcile pending→posted when SimpleFIN gives different IDs for the same transaction
  #
  # @param date [Date, String] Posted transaction date
  # @param amount [BigDecimal, Numeric] Transaction amount (must match exactly)
  # @param currency [String] Currency code
  # @param source [String] Provider name (e.g., "simplefin")
  # @param date_window [Integer] Days to search around the posted date (default: 8)
  # @return [Entry, nil] The pending entry, or nil when none or several match
  def find_pending_transaction(date:, amount:, currency:, source:, date_window: 8)
    date = Date.parse(date.to_s) unless date.is_a?(Date)

    # Look for entries that:
    # 1. Same account (implicit via account.entries)
    # 2. Same source (simplefin)
    # 3. Same amount (exact match - this is the strongest signal)
    # 4. Same currency
    # 5. Date within window (pending can post days later)
    # 6. Is a Transaction (not Trade or Valuation)
    # 7. Has pending=true in transaction.extra[<provider>]["pending"] for any provider
    #    in Transaction::PENDING_PROVIDERS
    candidates = account.entries
      .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
      .where(source: source)
      .where(amount: amount)
      .where(currency: currency)
      .where(date: (date - date_window.days)..date) # Pending must be ON or BEFORE posted date
      .where(Transaction.pending_sql("transactions"))
      .where(excluded: false)
      .limit(2)
      .to_a

    # Amount, currency and date alone cannot tell two same-amount pendings apart,
    # so only claim when the match is unambiguous (#2013). Otherwise the posted
    # transaction is imported as a new entry and the pendings stay for the
    # stale-pending cleanup.
    candidates.size == 1 ? candidates.first : nil
  end

  # Finds a pending transaction using fuzzy amount matching for tip adjustments
  # Used when exact amount matching fails - handles restaurant tips, adjusted authorizations, etc.
  #
  # IMPORTANT: Only returns a match if there's exactly ONE candidate to avoid false positives
  # with recurring merchant transactions (e.g., gas stations, coffee shops).
  #
  # @param date [Date, String] Posted transaction date
  # @param amount [BigDecimal, Numeric] Posted transaction amount (typically higher due to tip)
  # @param currency [String] Currency code
  # @param source [String] Provider name (e.g., "simplefin")
  # @param merchant_id [Integer, nil] Merchant ID for more accurate matching
  # @param name [String, nil] Transaction name for fuzzy name matching
  # @param date_window [Integer] Days to search backward from posted date (default: 3 for fuzzy)
  # @param amount_tolerance [Float] Maximum percentage difference allowed (default: 0.30 = 30%)
  # @return [Entry, nil] The pending entry or nil if not found/ambiguous
  def find_pending_transaction_fuzzy(date:, amount:, currency:, source:, merchant_id: nil, name: nil, date_window: 3, amount_tolerance: 0.30)
    date = Date.parse(date.to_s) unless date.is_a?(Date)
    amount = BigDecimal(amount.to_s)

    # Calculate amount bounds using ABS to handle both positive and negative amounts
    # Posted amount should be >= pending (tips add, not subtract)
    # Allow posted to be up to 30% higher than pending (covers typical tips)
    abs_amount = amount.abs
    min_pending_abs = abs_amount / (1 + amount_tolerance) # If posted is 100, pending could be as low as ~77
    max_pending_abs = abs_amount # Pending should not be higher than posted

    # Build base query for pending transactions
    # CRITICAL: Pending must be ON or BEFORE the posted date (authorization happens first)
    # Use tighter date window (3 days) - tips post quickly, not a week later
    # Use ABS() for amount comparison to handle negative amounts correctly
    candidates = account.entries
      .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
      .where(source: source)
      .where(currency: currency)
      .where(date: (date - date_window.days)..date) # Pending ON or BEFORE posted
      .where("ABS(entries.amount) BETWEEN ? AND ?", min_pending_abs, max_pending_abs)
      .where(Transaction.pending_sql("transactions"))

    # If merchant_id is provided, prioritize matching by merchant
    if merchant_id.present?
      merchant_matches = candidates.where("transactions.merchant_id = ?", merchant_id).to_a
      # Only match if exactly ONE candidate to avoid false positives
      return merchant_matches.first if merchant_matches.size == 1
      if merchant_matches.size > 1
        Rails.logger.info("Skipping fuzzy pending match: #{merchant_matches.size} ambiguous merchant candidates for amount=#{amount} date=#{date}")
      end
    end

    # If name is provided, try fuzzy name matching as fallback
    if name.present?
      # Extract first few significant words for comparison
      name_words = name.downcase.gsub(/[^a-z0-9\s]/, "").split.first(3).join(" ")
      if name_words.present?
        name_matches = candidates.select do |c|
          c_name_words = c.name.downcase.gsub(/[^a-z0-9\s]/, "").split.first(3).join(" ")
          name_words == c_name_words
        end
        # Only match if exactly ONE candidate to avoid false positives
        return name_matches.first if name_matches.size == 1
        if name_matches.size > 1
          Rails.logger.info("Skipping fuzzy pending match: #{name_matches.size} ambiguous name candidates for '#{name_words}' amount=#{amount} date=#{date}")
        end
      end
    end

    # No merchant or name match, return nil (too risky to match on amount alone)
    # This prevents false positives when multiple pending transactions exist
    nil
  end

  # Finds a pending transaction with low confidence (>30% to 100% amount difference)
  # Used for large tip scenarios where normal fuzzy matching would miss
  # Creates a "review recommended" suggestion rather than "possible duplicate"
  #
  # @param date [Date, String] Posted transaction date
  # @param amount [BigDecimal, Numeric] Posted transaction amount
  # @param currency [String] Currency code
  # @param source [String] Provider name
  # @param merchant_id [Integer, nil] Merchant ID for matching
  # @param name [String, nil] Transaction name for matching
  # @param date_window [Integer] Days to search backward (default: 3)
  # @return [Entry, nil] The pending entry or nil if not found/ambiguous
  def find_pending_transaction_low_confidence(date:, amount:, currency:, source:, merchant_id: nil, name: nil, date_window: 3)
    date = Date.parse(date.to_s) unless date.is_a?(Date)
    amount = BigDecimal(amount.to_s)

    # Allow up to 100% difference (e.g., $50 pending → $100 posted with huge tip)
    # This is low confidence - requires strong name/merchant match
    # Use ABS to handle both positive and negative amounts correctly
    abs_amount = amount.abs
    min_pending_abs = abs_amount / 2.0 # Posted could be up to 2x pending
    max_pending_abs = abs_amount * 0.77 # Pending must be at least 30% less (to not overlap with fuzzy)

    # Build base query for pending transactions
    # Use ABS() for amount comparison to handle negative amounts correctly
    candidates = account.entries
      .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
      .where(source: source)
      .where(currency: currency)
      .where(date: (date - date_window.days)..date)
      .where("ABS(entries.amount) BETWEEN ? AND ?", min_pending_abs, max_pending_abs)
      .where(Transaction.pending_sql("transactions"))

    # For low confidence, require BOTH merchant AND name match (stronger signal needed)
    if merchant_id.present? && name.present?
      name_words = name.downcase.gsub(/[^a-z0-9\s]/, "").split.first(3).join(" ")
      return nil if name_words.blank?

      merchant_matches = candidates.where("transactions.merchant_id = ?", merchant_id).to_a
      name_matches = merchant_matches.select do |c|
        c_name_words = c.name.downcase.gsub(/[^a-z0-9\s]/, "").split.first(3).join(" ")
        name_words == c_name_words
      end

      # Only match if exactly ONE candidate
      return name_matches.first if name_matches.size == 1
    end

    nil
  end

  # Stores a duplicate suggestion on a pending entry for user review
  # The suggestion is stored in the pending transaction's extra field
  #
  # @param pending_entry [Entry] The pending entry that may be a duplicate
  # @param posted_entry [Entry] The posted entry it may match
  # @param reason [String] Why this was flagged (e.g., "fuzzy_amount_match", "low_confidence_match")
  # @param posted_amount [BigDecimal] The posted transaction amount
  # @param confidence [String] Confidence level: "medium" (≤30% diff) or "low" (>30% diff)
  def store_duplicate_suggestion(pending_entry:, posted_entry:, reason:, posted_amount:, confidence: "medium")
    return unless pending_entry&.entryable.is_a?(Transaction)

    pending_transaction = pending_entry.entryable
    existing_extra = pending_transaction.extra || {}

    # Don't overwrite if already has a suggestion (keep first one found)
    return if existing_extra["potential_posted_match"].present?

    # Don't suggest if the posted entry is also still pending (pending→pending match)
    # Suggestions are only for pending→posted reconciliation
    posted_transaction = posted_entry.entryable
    return if posted_transaction.is_a?(Transaction) && posted_transaction.pending?

    pending_transaction.update!(
      extra: existing_extra.merge(
        "potential_posted_match" => {
          "entry_id" => posted_entry.id,
          "reason" => reason,
          "posted_amount" => posted_amount.to_s,
          "confidence" => confidence,
          "detected_at" => Date.current.to_s
        }
      )
    )
  end

  # Auto-detects investment activity label from transaction name and amount
  # Only detects extremely obvious cases to maintain high accuracy
  # Users can always manually adjust the label afterward
  #
  # @param name [String] Transaction name/description
  # @param amount [BigDecimal, Numeric] Transaction amount (positive or negative)
  # @return [String, nil] Detected activity label or nil if no pattern matches
  def detect_activity_label(name, amount)
    return nil if name.blank?

    name_lower = name.downcase.strip

    # Only detect the most obvious patterns - be conservative to avoid false positives
    # Users can manually adjust labels for edge cases
    case name_lower
    when /^dividend\b/, /\bdividend payment\b/, /\bqualified dividend\b/, /\bordinary dividend\b/
      "Dividend"
    when /^interest\b/, /\binterest income\b/, /\binterest payment\b/
      "Interest"
    when /^fee\b/, /\bmanagement fee\b/, /\badvisory fee\b/, /\btransaction fee\b/
      "Fee"
    when /\bemployer match\b/, /\bemployer contribution\b/
      "Contribution"
    when /\b401[k\(]/, /\bira contribution\b/, /\broth contribution\b/
      "Contribution"
    else
      nil # Let user categorize manually - default to nil for safety
    end
  end

  # Determines why an entry should be skipped during sync.
  # Returns nil if entry should NOT be skipped.
  #
  # @param entry [Entry] The entry to check
  # @return [String, nil] Skip reason or nil if entry can be synced
  def determine_skip_reason(entry)
    return "excluded" if entry.excluded?
    return "user_modified" if entry.user_modified?
    return "import_locked" if entry.import_locked?
    nil
  end

  # Records a skipped entry for stats collection.
  #
  # @param entry [Entry] The entry that was skipped
  # @param reason [String] Why it was skipped
  def record_skip(entry, reason)
    @skipped_entries << {
      id: entry.id,
      name: entry.name,
      reason: reason,
      external_id: entry.external_id,
      account_name: entry.account.name
    }
  end

  # Moves the user's corrections on a provider row that is about to be removed
  # onto the row import_holding carries corrections from: the latest one of
  # the same provider security on or before `date`. Returns that row, or nil
  # when there is none or nothing to move.
  def carry_corrections_back(from:, date:)
    corrections = corrections_from(from, provider_security_id: from.provider_security_id || from.security_id)
    return if corrections.empty?

    target = previous_holding_for(security: from.provider_security || from.security, currency: from.currency,
                                  date: date + 1, account_provider_id: from.account_provider_id)
    return if target.nil?

    # A remap onto a security the target's date already holds would break the
    # unique (account, security, date, currency) index. The target folds into
    # that row instead, as Holding#remap_security! merges a collision. Another
    # provider's row is that provider's position and is never folded into: the
    # target keeps its own security and the remap is dropped, which is logged.
    collision = corrections.key?(:security) &&
      account.holdings.where.not(id: target.id)
        .find_by(security: corrections[:security], date: target.date, currency: target.currency)
    return target.tap { |row| row.update!(corrections) } unless collision

    if collision.account_provider_id.present? && collision.account_provider_id != target.account_provider_id
      Rails.logger.warn(
        "ProviderImportAdapter: cross-provider remap collision for account=#{account.id} security=#{corrections[:security].id} date=#{target.date} currency=#{target.currency}; keeping existing id=#{collision.id}"
      )
      return target.tap { |row| row.update!(corrections.except(:security, :provider_security_id, :security_locked)) }
    end

    target.assign_attributes(corrections.except(:security, :provider_security_id, :security_locked))
    merge_holding_into!(target, collision)
  end

  private
    # Folds `holding` into `existing`, a row of another security on the same
    # date and currency, with the arithmetic of Holding#remap_security!'s
    # collision merge: quantities and amounts add, cost basis is the weighted
    # average when both have one, and the provider tracking moves across.
    # Returns `existing`.
    def merge_holding_into!(holding, existing)
      merged_qty = existing.qty + holding.qty
      merged_amount = existing.amount + holding.amount
      merged_cost_basis = if existing.cost_basis.present? && holding.cost_basis.present? && merged_qty.positive?
        ((existing.cost_basis * existing.qty) + (holding.cost_basis * holding.qty)) / merged_qty
      else
        existing.cost_basis
      end

      merge_attrs = {
        qty: merged_qty,
        amount: merged_amount,
        price: merged_qty.positive? ? merged_amount / merged_qty : 0,
        cost_basis: merged_cost_basis,
        security_locked: true
      }
      merge_attrs[:external_id] = holding.external_id if existing.external_id.blank? && holding.external_id.present?
      merge_attrs[:provider_security_id] = holding.provider_security_id || holding.security_id if existing.provider_security_id.blank?
      merge_attrs[:account_provider_id] = holding.account_provider_id if existing.account_provider_id.blank? && holding.account_provider_id.present?

      Holding.transaction(requires_new: true) do
        holding.destroy!
        existing.update!(merge_attrs)
      end
      existing
    end

    # The user's corrections a row holds: a remapped security and a locked
    # cost basis, as attributes for the row that takes them over.
    def corrections_from(holding, provider_security_id:)
      corrections = {}
      if holding&.security_locked?
        corrections[:security] = holding.security
        corrections[:provider_security_id] = holding.provider_security_id || provider_security_id
        corrections[:security_locked] = true
      end
      if holding&.cost_basis_locked?
        corrections[:cost_basis] = holding.cost_basis
        corrections[:cost_basis_source] = holding.cost_basis_source
        corrections[:cost_basis_locked] = true
      end
      corrections
    end

    # The latest earlier holding of the security the provider reports. A
    # remapped row records that security in provider_security_id; an
    # unremapped one has it as its own security. A provider that reports the
    # user's chosen security instead still finds the row the user locked to
    # it. Only the latest row counts, so a correction the user has since
    # undone is not revived from an older day.
    #
    # Within that day, a row recording this provider security is the position
    # it came from, and wins over a correction locked to it: with chained
    # remaps (A onto B, B onto C) an incoming B matches both the B->C row and
    # the A->B row on the same date. `id` settles anything left, so the pick
    # never depends on the query plan.
    def previous_holding_for(security:, currency:, date:, account_provider_id:)
      scope = account.holdings
        .where(currency: currency)
        .where("holdings.date < ?", date)
        .where(
          "holdings.provider_security_id = :id OR (holdings.provider_security_id IS NULL AND holdings.security_id = :id) " \
          "OR (holdings.security_locked AND holdings.security_id = :id)",
          id: security.id
        )
      scope = scope.where(account_provider_id: account_provider_id) if account_provider_id.present?

      match_rank = ActiveRecord::Base.sanitize_sql_array([
        "CASE WHEN holdings.provider_security_id = :id THEN 0 " \
        "WHEN holdings.provider_security_id IS NULL AND holdings.security_id = :id THEN 1 ELSE 2 END",
        id: security.id
      ])
      scope.order(date: :desc).order(Arel.sql(match_rank)).order(:id).first
    end

    # Loads the transfer together with both legs, their entries and accounts in
    # one joined query, so Transfer#kind_for_leg reads them without the lazy
    # loads it would otherwise pay on every re-imported row. Looked up per row
    # rather than memoized per adapter: most processors build an adapter per
    # row, and some link or destroy transfers mid-sync (Trade Republic), so a
    # memo would be both costlier and stale.
    def matched_transfer_for(entry)
      return nil unless entry.persisted?

      transaction_id = entry.transaction.id
      transfers = Transfer.eager_load(inflow_transaction: { entry: :account }, outflow_transaction: { entry: :account })
      transfers.where(inflow_transaction_id: transaction_id).or(transfers.where(outflow_transaction_id: transaction_id)).first
    end

    # Memoized per adapter instance (which is per-account). Membership in
    # goal_accounts is stable across a sync batch.
    def account_linked_to_any_goal?
      return @account_linked_to_any_goal if defined?(@account_linked_to_any_goal)

      @account_linked_to_any_goal = account.linked_to_goal?
    end

    # Writes provider-owned metadata onto the transaction.
    #
    # Namespaces named in replace_extra_namespaces are snapshots, not
    # accumulations: the whole branch is dropped before merging, so a nested key
    # the provider stopped sending disappears with it. deep_merge alone recurses
    # into nested hashes, so a removed payment_meta.payee would otherwise survive
    # forever and the drawer would keep showing it. Only namespaces the incoming
    # payload actually carries are replaced.
    #
    # @param entry [Entry] the entry being imported
    # @param extra [Hash, nil] provider metadata to apply
    # @param replace_extra_namespaces [Array<String>] branches to replace wholesale
    # @return [void]
    def apply_provider_extra(entry, extra, replace_extra_namespaces)
      return unless extra.present? && entry.entryable.is_a?(Transaction)

      existing = entry.transaction.extra || {}
      incoming = extra.is_a?(Hash) ? extra.deep_stringify_keys : {}
      replaced = replace_extra_namespaces.map(&:to_s).select { |ns| incoming.key?(ns) }

      entry.transaction.extra = existing.except(*replaced).deep_merge(incoming)
      entry.transaction.save!
    end

    # A protected entry keeps its name, so the values that name was built from have
    # to stay as well. Rule::ConditionFilter::TransactionName rebuilds a Plaid name
    # from the stored original_description; refreshing that value while the name
    # stays put would make the rebuilt name disagree with the real one, and flip
    # `=` and `!=` rules on the entry. The drawer shows the kept value too, so it
    # agrees with the name the user sees.
    #
    # A key with nothing stored yet takes the incoming value: a row imported before
    # the key existed was never combined, so there is nothing to keep in step.
    #
    # @param entry [Entry] the protected entry
    # @param owned [Hash, nil] the incoming namespaces the provider owns
    # @param name_extra_keys [Hash{String=>Array<String>}] keys the name was built from
    # @return [Hash, nil] owned, with those keys carried over from what is stored
    def keep_name_sources(entry, owned, name_extra_keys)
      return owned if owned.blank? || name_extra_keys.blank?

      stored = entry.transaction.extra || {}
      name_extra_keys.each do |namespace, keys|
        ns = namespace.to_s
        next unless owned[ns].is_a?(Hash) && stored[ns].is_a?(Hash)

        Array(keys).map(&:to_s).each do |key|
          owned[ns][key] = stored[ns][key] if stored[ns].key?(key)
        end
      end

      owned
    end

    # Removes the pending flag every provider writes under its own namespace,
    # dropping a namespace that held nothing else. Used when a booked version of
    # a transaction arrives and the stale flag would otherwise stick forever.
    #
    # @param extra [Hash, nil] the transaction's current extra
    # @return [Hash] a copy with the pending flags removed
    def clear_pending_flags_from_extra(extra)
      ex = (extra || {}).deep_dup
      ex = {} unless ex.is_a?(Hash)
      Transaction::PENDING_PROVIDERS.each do |provider|
        next unless ex.key?(provider)
        next unless ex[provider].is_a?(Hash)
        ex[provider].delete("pending")
        ex.delete(provider) if ex[provider].empty?
      end
      ex
    end
end