Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
110 KB
Raw Blame
require "test_helper"

class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCase
  include SecuritiesTestHelper

  setup do
    @family = families(:dylan_family)
    @snaptrade_item = snaptrade_items(:configured_item)
    @snaptrade_account = snaptrade_accounts(:fidelity_401k)

    # Create a linked Sure account for the SnapTrade account
    @account = @family.accounts.create!(
      name: "Test Investment",
      balance: 50000,
      cash_balance: 1000,
      currency: "USD",
      accountable: Investment.new
    )

    # Link the SnapTrade account to the Sure account
    @snaptrade_account.ensure_account_provider!(@account)
    @snaptrade_account.reload
  end

  test "processes buy trade activity" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_trade_activity(
        id: "trade_001",
        type: "BUY",
        symbol: "AAPL",
        units: 10,
        price: 150.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    # Verify a trade was created (external_id is on entry, not trade)
    entry = @account.entries.find_by(external_id: "trade_001", source: "snaptrade")
    assert_not_nil entry, "Entry should be created"
    assert entry.entryable.is_a?(Trade), "Entry should be a Trade"

    trade = entry.entryable
    assert_equal 10, trade.qty
    assert_equal 150.00, trade.price.to_f
    assert_equal "Buy", trade.investment_activity_label
  end

  test "processes sell trade activity with negative quantity" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_trade_activity(
        id: "trade_002",
        type: "SELL",
        symbol: "AAPL",
        units: 5,
        price: 160.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    entry = @account.entries.find_by(external_id: "trade_002", source: "snaptrade")
    assert_not_nil entry
    trade = entry.entryable
    assert_equal(-5, trade.qty)  # Sell should be negative
    assert_equal "Sell", trade.investment_activity_label
  end

  test "the trade amount, qty, price, and fee reported by SnapTrade are respected" do
    process_activities(
      build_trade_activity(id: "buy_rounded", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: -101.00, fee: 1.00)
    )

    entry = snaptrade_entry("buy_rounded")
    assert_equal BigDecimal("101"), entry.amount
    assert_equal BigDecimal("3"), entry.entryable.qty
    assert_equal BigDecimal("33.33"), entry.entryable.price
    assert_equal BigDecimal("1.00"), entry.entryable.fee
  end

  test "fractional share quantity is stored exactly" do
    process_activities(
      build_trade_activity(id: "buy_fractional", type: "BUY", symbol: "VTI", units: 0.12345678, price: 149.94, amount: -18.51)
    )

    entry = snaptrade_entry("buy_fractional")
    assert_equal BigDecimal("0.12345678"), entry.entryable.qty
    assert_equal BigDecimal("18.51"), entry.amount
  end

  test "trade direction comes from the activity type, not the sign of SnapTrade's amount" do
    process_activities(
      build_trade_activity(id: "buy_positive_amount", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: 100.00),
      build_trade_activity(id: "sell_negative_amount", type: "SELL", symbol: "AAPL", units: 7, price: 14.29, amount: -100.00)
    )

    assert_equal BigDecimal("100"), snaptrade_entry("buy_positive_amount").amount
    assert_equal BigDecimal("-100"), snaptrade_entry("sell_negative_amount").amount
  end

  test "records the trade fee as a cost regardless of the sign SnapTrade gives it" do
    process_activities(
      build_trade_activity(id: "buy_negative_fee", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1504.95, fee: -4.95)
    )

    assert_equal BigDecimal("4.95"), snaptrade_entry("buy_negative_fee").entryable.fee
  end

  test "a zero reported amount falls back to qty times price" do
    process_activities(
      build_trade_activity(id: "buy_zero_amount", type: "BUY", symbol: "AAPL", units: 2, price: 50.00, amount: 0)
    )

    assert_equal BigDecimal("100"), snaptrade_entry("buy_zero_amount").amount
  end

  test "when amount is not reported, the fallback amount includes the fee like a manually entered trade" do
    process_activities(
      build_trade_activity(id: "buy_no_amount", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, fee: 4.95),
      build_trade_activity(id: "sell_no_amount", type: "SELL", symbol: "AAPL", units: 10, price: 150.00, fee: 4.95)
    )

    assert_equal BigDecimal("1504.95"), snaptrade_entry("buy_no_amount").amount
    assert_equal BigDecimal("-1495.05"), snaptrade_entry("sell_no_amount").amount
  end

  test "imports the trade with a price derived from amount and units, and creates debug log, when price is missing" do
    process_activities(
      build_trade_activity(id: "buy_no_price", type: "BUY", symbol: "AAPL", units: 4, price: nil, amount: -100.00)
    )

    entry = snaptrade_entry("buy_no_price")
    assert_not_nil entry, "a trade with units and amount but no price must still be imported"
    assert_equal BigDecimal("25"), entry.entryable.price
    assert_equal BigDecimal("4"), entry.entryable.qty
    assert_equal BigDecimal("100"), entry.amount

    log = snaptrade_debug_log("buy_no_price", level: "info")
    assert_equal "derived_price", log&.metadata&.dig("reason")
    assert_equal "25.0", log&.metadata&.dig("derived_price")
  end

  test "imports a fully reported trade without creating debug log" do
    process_activities(
      build_trade_activity(id: "buy_complete", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: -101.00, fee: 1.00)
    )

    assert_not_nil snaptrade_entry("buy_complete")
    assert DebugLogEntry.where(provider_key: "snaptrade").none? { |log| log.metadata["activity_id"] == "buy_complete" },
           "routine trades must not flood /settings/debug"
  end

  test "a price derived from amount and units excludes the fee for buys and sells" do
    process_activities(
      build_trade_activity(id: "buy_no_price_fee", type: "BUY", symbol: "AAPL", units: 10, price: nil, amount: -1505.00, fee: 5.00),
      build_trade_activity(id: "sell_no_price_fee", type: "SELL", symbol: "AAPL", units: 10, price: nil, amount: 1495.00, fee: 5.00)
    )

    assert_equal BigDecimal("150"), snaptrade_entry("buy_no_price_fee").entryable.price
    assert_equal BigDecimal("150"), snaptrade_entry("sell_no_price_fee").entryable.price
  end

  test "resyncing keeps the stored fee when SnapTrade omits it, but applies a reported zero" do
    process_activities(
      build_trade_activity(id: "buy_fee_omitted", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1504.95, fee: 4.95)
    )

    process_activities(
      build_trade_activity(id: "buy_fee_omitted", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1504.95)
    )
    assert_equal BigDecimal("4.95"), snaptrade_entry("buy_fee_omitted").entryable.reload.fee

    process_activities(
      build_trade_activity(id: "buy_fee_omitted", type: "BUY", symbol: "AAPL", units: 10, price: 150.00, amount: -1500.00, fee: 0)
    )
    assert_equal BigDecimal("0"), snaptrade_entry("buy_fee_omitted").entryable.reload.fee
  end

  test "resyncing corrects the amount of a previously imported trade" do
    process_activities(
      build_trade_activity(id: "buy_resync", type: "BUY", symbol: "AAPL", units: 3, price: 33.33)
    )
    assert_equal BigDecimal("99.99"), snaptrade_entry("buy_resync").amount

    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_trade_activity(id: "buy_resync", type: "BUY", symbol: "AAPL", units: 3, price: 33.33, amount: -100.00)
      )
    end

    assert_equal BigDecimal("100"), snaptrade_entry("buy_resync").amount
  end

  test "processes dividend cash activity as negative inflow" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_cash_activity(
        id: "div_001",
        type: "DIVIDEND",
        amount: 25.50,
        settlement_date: Date.current.to_s,
        symbol: "VTI"
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    entry = @account.entries.find_by(external_id: "div_001", source: "snaptrade")
    assert_not_nil entry, "Entry should be created"
    assert entry.entryable.is_a?(Transaction), "Entry should be a Transaction"

    transaction = entry.entryable
    assert_equal(-25.50, entry.amount.to_f)
    assert_equal "Dividend", transaction.investment_activity_label
  end

  test "processes contribution with negative inflow amount" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_cash_activity(
        id: "contrib_001",
        type: "CONTRIBUTION",
        amount: 500.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    entry = @account.entries.find_by(external_id: "contrib_001", source: "snaptrade")
    assert_not_nil entry
    assert_equal(-500.00, entry.amount.to_f)
    assert_equal "Contribution", entry.entryable.investment_activity_label
  end

  test "processes withdrawal with positive outflow amount" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_cash_activity(
        id: "withdraw_001",
        type: "WITHDRAWAL",
        amount: 200.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    entry = @account.entries.find_by(external_id: "withdraw_001", source: "snaptrade")
    assert_not_nil entry
    assert_equal 200.00, entry.amount.to_f
    assert_equal "Withdrawal", entry.entryable.investment_activity_label
  end

  test "processes transfers with Sure sign convention" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_cash_activity(
        id: "transfer_in_001",
        type: "TRANSFER_IN",
        amount: 300.00,
        settlement_date: Date.current.to_s
      ),
      build_cash_activity(
        id: "transfer_out_001",
        type: "TRANSFER_OUT",
        amount: 125.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    transfer_in = @account.entries.find_by(external_id: "transfer_in_001", source: "snaptrade")
    transfer_out = @account.entries.find_by(external_id: "transfer_out_001", source: "snaptrade")

    assert_not_nil transfer_in
    assert_not_nil transfer_out
    assert_equal(-300.00, transfer_in.amount.to_f)
    assert_equal 125.00, transfer_out.amount.to_f
    assert_equal "Transfer", transfer_in.entryable.investment_activity_label
    assert_equal "Transfer", transfer_out.entryable.investment_activity_label
  end

  test "normalizes bare TRANSFER from the provider sign" do
    # Regression test for issue #2756. Unlike TRANSFER_IN/TRANSFER_OUT, a bare "TRANSFER"
    # carries no direction in the type, so SnapTrade's sign is the only directional signal
    # available and must be inverted into Sure's convention rather than passed through.
    @snaptrade_account.update!(raw_activities_payload: [
      build_cash_activity(
        id: "transfer_generic_in",
        type: "TRANSFER",
        amount: 1320.75,
        settlement_date: Date.current.to_s
      ),
      build_cash_activity(
        id: "transfer_generic_out",
        type: "TRANSFER",
        amount: -500.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    inbound = @account.entries.find_by(external_id: "transfer_generic_in", source: "snaptrade")
    outbound = @account.entries.find_by(external_id: "transfer_generic_out", source: "snaptrade")

    assert_not_nil inbound
    assert_not_nil outbound
    assert_equal(-1320.75, inbound.amount.to_f, "money in must be stored negative on an asset account")
    assert_equal 500.00, outbound.amount.to_f, "money out must be stored positive on an asset account"
  end

  test "processes TRANSFER as cash transaction even when units are present in payload" do
    # In 401(k) accounts, payroll contributions arrive as type: TRANSFER with units and cash amount
    process_activities(
      build_trade_activity(
        id: "xfer_payroll_contrib",
        type: "TRANSFER",
        symbol: "5022",
        units: 8.699,
        price: 156.36,
        amount: 1388.84
      )
    )

    entry = snaptrade_entry("xfer_payroll_contrib")
    assert_not_nil entry
    assert entry.entryable.is_a?(Transaction), "TRANSFER must be processed as a cash Transaction"
    assert_equal BigDecimal("-1388.84"), entry.amount, "cash contribution amount must be preserved as negative inflow"
    assert_equal "Transfer", entry.entryable.investment_activity_label
  end

  test "keeps cash TRANSFER with zero units on the cash transaction path" do
    process_activities(
      build_cash_activity(
        id: "xfer_cash_zero_units",
        type: "TRANSFER",
        amount: 250.00,
        settlement_date: Date.current.to_s
      ).merge("units" => 0)
    )

    entry = snaptrade_entry("xfer_cash_zero_units")
    assert_not_nil entry
    assert entry.entryable.is_a?(Transaction), "cash transfer with 0 units must remain a Transaction"
    assert_equal(-250.00, entry.amount.to_f)
    assert_equal "Transfer", entry.entryable.investment_activity_label
  end

  test "processes REBATE as negative cash inflow" do
    process_activities(
      build_cash_activity(id: "rebate_001", type: "REBATE", amount: 50.00, settlement_date: Date.current.to_s)
    )

    entry = snaptrade_entry("rebate_001")
    assert_not_nil entry
    assert_equal(-50.00, entry.amount.to_f, "rebate credited to account must be stored as negative inflow")
    assert_equal "Other", entry.entryable.investment_activity_label
  end

  test "processes REIMBURSEMENT and PROMOTION as negative cash inflows" do
    process_activities(
      build_cash_activity(id: "reimb_001", type: "REIMBURSEMENT", amount: 216.23, settlement_date: Date.current.to_s),
      build_cash_activity(id: "promo_001", type: "PROMOTION", amount: 5.00, settlement_date: Date.current.to_s)
    )

    reimbursement = snaptrade_entry("reimb_001")
    promotion = snaptrade_entry("promo_001")

    assert_not_nil reimbursement
    assert_not_nil promotion
    assert_equal(-216.23, reimbursement.amount.to_f, "cashback paid into the account must be stored as an inflow")
    assert_equal(-5.00, promotion.amount.to_f, "a promotional bonus must be stored as an inflow")
    assert_equal "Other", reimbursement.entryable.investment_activity_label
  end

  test "processes a negative REIMBURSEMENT (clawback) as an outflow" do
    process_activities(
      build_cash_activity(id: "reimb_neg_001", type: "REIMBURSEMENT", amount: -12.50, settlement_date: Date.current.to_s)
    )

    entry = snaptrade_entry("reimb_neg_001")
    assert_not_nil entry
    assert_equal 12.50, entry.amount.to_f
  end

  test "processes RETURN_OF_CAPITAL, DISTRIBUTION, and SUBSTITUTE_DIVIDEND as negative cash inflows with Dividend label" do
    process_activities(
      build_cash_activity(id: "roc_001", type: "RETURN_OF_CAPITAL", amount: 75.00, settlement_date: Date.current.to_s, symbol: "VTI"),
      build_cash_activity(id: "dist_001", type: "DISTRIBUTION", amount: 120.00, settlement_date: Date.current.to_s, symbol: "VNQ"),
      build_cash_activity(id: "sub_div_001", type: "SUBSTITUTE_DIVIDEND", amount: 45.00, settlement_date: Date.current.to_s, symbol: "AAPL")
    )

    roc = snaptrade_entry("roc_001")
    dist = snaptrade_entry("dist_001")
    sub_div = snaptrade_entry("sub_div_001")

    assert_not_nil roc
    assert_not_nil dist
    assert_not_nil sub_div
    assert_equal(-75.00, roc.amount.to_f)
    assert_equal "Dividend", roc.entryable.investment_activity_label
    assert_equal(-120.00, dist.amount.to_f)
    assert_equal "Dividend", dist.entryable.investment_activity_label
    assert_equal(-45.00, sub_div.amount.to_f)
    assert_equal "Dividend", sub_div.entryable.investment_activity_label
  end

  test "processes card purchases as outflows and refunds and payments as inflows" do
    process_activities(
      build_cash_activity(id: "purchase_001", type: "POSDEBIT", amount: -32.73, settlement_date: Date.current.to_s),
      build_cash_activity(id: "refund_001", type: "POSCREDIT", amount: 10.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "payment_001", type: "PAYMENT", amount: 500.00, settlement_date: Date.current.to_s)
    )

    assert_equal 32.73, snaptrade_entry("purchase_001").amount.to_f
    assert_equal(-10.00, snaptrade_entry("refund_001").amount.to_f)
    assert_equal(-500.00, snaptrade_entry("payment_001").amount.to_f)
  end

  test "a card payment with no matched bank side is a transfer, not income" do
    card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
    @snaptrade_account.ensure_account_provider!(card)
    @snaptrade_account.reload

    process_activities(
      build_cash_activity(id: "payment_002", type: "PAYMENT", amount: 500.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "purchase_002", type: "POSDEBIT", amount: -32.73, settlement_date: Date.current.to_s)
    )

    payment = card.entries.find_by!(external_id: "payment_002", source: "snaptrade")
    assert_equal(-500.00, payment.amount.to_f)
    assert_equal "funds_movement", payment.entryable.kind
    assert_equal "standard", card.entries.find_by!(external_id: "purchase_002", source: "snaptrade").entryable.kind
  end

  # SnapTrade links a line of credit without "card" in its type as a Loan.
  # Account::ProviderImportAdapter already classifies money into a linked Loan
  # as loan_payment (a transfer kind), so only cards needed card_payment_kind.
  test "a payment into a line of credit linked as a loan is a loan payment, not income" do
    loan = @family.accounts.create!(name: "Line of credit", balance: 0, currency: "USD", accountable: Loan.new)
    @snaptrade_account.ensure_account_provider!(loan)
    @snaptrade_account.reload

    process_activities(
      build_cash_activity(id: "payment_003", type: "PAYMENT", amount: 300.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "purchase_003", type: "POSDEBIT", amount: -40.00, settlement_date: Date.current.to_s)
    )

    payment = loan.entries.find_by!(external_id: "payment_003", source: "snaptrade").entryable
    assert_equal "loan_payment", payment.kind
    assert_includes Transaction::TRANSFER_KINDS, payment.kind
    assert_equal "standard", loan.entries.find_by!(external_id: "purchase_003", source: "snaptrade").entryable.kind
  end

  test "processes cash FEE and TAX as positive outflow and INTEREST as negative inflow" do
    process_activities(
      build_cash_activity(id: "fee_001", type: "FEE", amount: -25.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "tax_001", type: "TAX", amount: 15.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "interest_001", type: "INTEREST", amount: 12.50, settlement_date: Date.current.to_s)
    )

    fee = snaptrade_entry("fee_001")
    tax = snaptrade_entry("tax_001")
    interest = snaptrade_entry("interest_001")

    assert_not_nil fee
    assert_not_nil tax
    assert_not_nil interest

    assert_equal 25.00, fee.amount.to_f
    assert_equal "Fee", fee.entryable.investment_activity_label

    assert_equal 15.00, tax.amount.to_f
    assert_equal "Fee", tax.entryable.investment_activity_label

    assert_equal(-12.50, interest.amount.to_f)
    assert_equal "Interest", interest.entryable.investment_activity_label
  end

  test "processes INTERNAL_CASH_TRANSFER_IN and OUT with correct signs" do
    process_activities(
      build_cash_activity(id: "int_cash_in", type: "INTERNAL_CASH_TRANSFER_IN", amount: 250.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "int_cash_out", type: "INTERNAL_CASH_TRANSFER_OUT", amount: 100.00, settlement_date: Date.current.to_s)
    )

    inbound = snaptrade_entry("int_cash_in")
    outbound = snaptrade_entry("int_cash_out")

    assert_not_nil inbound
    assert_not_nil outbound
    assert_equal(-250.00, inbound.amount.to_f)
    assert_equal "Transfer", inbound.entryable.investment_activity_label
    assert_equal 100.00, outbound.amount.to_f
    assert_equal "Transfer", outbound.entryable.investment_activity_label
  end

  test "processes cash ADJUSTMENT by inverting provider sign" do
    process_activities(
      build_cash_activity(id: "adj_credit", type: "ADJUSTMENT", amount: 15.00, settlement_date: Date.current.to_s),
      build_cash_activity(id: "adj_debit", type: "ADJUSTMENT", amount: -20.00, settlement_date: Date.current.to_s)
    )

    credit = snaptrade_entry("adj_credit")
    debit = snaptrade_entry("adj_debit")

    assert_not_nil credit
    assert_not_nil debit
    assert_equal(-15.00, credit.amount.to_f, "credit adjustment must be stored as negative inflow")
    assert_equal 20.00, debit.amount.to_f, "debit adjustment must be stored as positive outflow"
  end

  test "processes forward SPLIT as zero-cash trade adding shares (LAB-156)" do
    process_activities(
      build_trade_activity(
        id: "split_001",
        type: "SPLIT",
        symbol: "VGT",
        units: 3010.014,
        price: 0.0,
        amount: 304071.61 # SnapTrade notional value must NOT become a cash withdrawal
      )
    )

    entry = snaptrade_entry("split_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade), "SPLIT must be imported as a Trade, not a cash Transaction"
    trade = entry.entryable
    assert_equal BigDecimal("3010.014"), trade.qty
    assert_equal BigDecimal("0"), trade.price
    assert_equal BigDecimal("0"), entry.amount, "cash impact must be zero to prevent balance distortion"
    assert_equal "Other", trade.investment_activity_label
  end

  test "processes REVERSE_SPLIT as zero-cash trade with negative quantity" do
    process_activities(
      build_trade_activity(
        id: "rev_split_001",
        type: "REVERSE_SPLIT",
        symbol: "SOXL",
        units: 50.0,
        price: 0.0
      )
    )

    entry = snaptrade_entry("rev_split_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    trade = entry.entryable
    assert_equal BigDecimal("-50.0"), trade.qty
    assert_equal BigDecimal("0"), trade.price
    assert_equal BigDecimal("0"), entry.amount
    assert_equal "Other", trade.investment_activity_label
  end

  test "processes STOCK_DIVIDEND as zero-cash trade with Dividend label" do
    process_activities(
      build_trade_activity(
        id: "stock_div_001",
        type: "STOCK_DIVIDEND",
        symbol: "AAPL",
        units: 2.0,
        price: 0.0
      )
    )

    entry = snaptrade_entry("stock_div_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    trade = entry.entryable
    assert_equal BigDecimal("2.0"), trade.qty
    assert_equal BigDecimal("0"), trade.price
    assert_equal BigDecimal("0"), entry.amount
    assert_equal "Dividend", trade.investment_activity_label
  end

  test "processes SPINOFF as zero-cash trade" do
    process_activities(
      build_trade_activity(
        id: "spinoff_001",
        type: "SPINOFF",
        symbol: "GEV",
        units: 10.0,
        price: 0.0
      )
    )

    entry = snaptrade_entry("spinoff_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    trade = entry.entryable
    assert_equal BigDecimal("10.0"), trade.qty
    assert_equal BigDecimal("0"), trade.price
    assert_equal BigDecimal("0"), entry.amount
    assert_equal "Other", trade.investment_activity_label
  end

  test "processes OPTIONASSIGNMENT and OPTIONEXERCISE as trades" do
    process_activities(
      build_trade_activity(
        id: "opt_assign_001",
        type: "OPTIONASSIGNMENT",
        symbol: "AAPL",
        units: 1.0,
        price: 150.0
      ),
      build_trade_activity(
        id: "opt_exercise_001",
        type: "OPTIONEXERCISE",
        symbol: "MSFT",
        units: 1.0,
        price: 300.0
      ),
      build_trade_activity(
        id: "opt_exercise_close",
        type: "OPTIONEXERCISE",
        symbol: "QQQ",
        units: -1.0,
        price: 0.0,
        amount: -23805.0 # Exercise cash outlay
      )
    )

    assign = snaptrade_entry("opt_assign_001")
    exercise = snaptrade_entry("opt_exercise_001")
    exercise_close = snaptrade_entry("opt_exercise_close")

    assert_not_nil assign
    assert_not_nil exercise
    assert_not_nil exercise_close
    assert assign.entryable.is_a?(Trade)
    assert exercise.entryable.is_a?(Trade)
    assert exercise_close.entryable.is_a?(Trade)
    assert_equal BigDecimal("-1.0"), assign.entryable.qty, "assignment should be sell-side (negative)"
    assert_equal BigDecimal("1.0"), exercise.entryable.qty
    assert_equal BigDecimal("-1.0"), exercise_close.entryable.qty, "negative units removes exercised contract"
  end

  test "processes EXTERNAL_ASSET_TRANSFER_IN and OUT as zero-cash asset trades" do
    process_activities(
      build_trade_activity(
        id: "acat_in_001",
        type: "EXTERNAL_ASSET_TRANSFER_IN",
        symbol: "VTI",
        units: 100.0,
        price: 220.0
      ),
      build_trade_activity(
        id: "acat_out_001",
        type: "EXTERNAL_ASSET_TRANSFER_OUT",
        symbol: "VXUS",
        units: 50.0,
        price: 60.0
      )
    )

    inbound = snaptrade_entry("acat_in_001")
    outbound = snaptrade_entry("acat_out_001")

    assert_not_nil inbound
    assert_not_nil outbound
    assert inbound.entryable.is_a?(Trade)
    assert outbound.entryable.is_a?(Trade)
    assert_equal BigDecimal("100.0"), inbound.entryable.qty
    assert_equal BigDecimal("-50.0"), outbound.entryable.qty
    assert_equal BigDecimal("0"), inbound.amount, "ACAT transfer in has zero cash flow"
    assert_equal BigDecimal("0"), outbound.amount, "ACAT transfer out has zero cash flow"
    assert_equal "Transfer", inbound.entryable.investment_activity_label
    assert_equal "Transfer", outbound.entryable.investment_activity_label
  end

  test "processes INTERNAL_ASSET_TRANSFER_IN and OUT as zero-cash asset trades" do
    process_activities(
      build_trade_activity(
        id: "int_asset_in_001",
        type: "INTERNAL_ASSET_TRANSFER_IN",
        symbol: "VTI",
        units: 25.0,
        price: 220.0
      ),
      build_trade_activity(
        id: "int_asset_out_001",
        type: "INTERNAL_ASSET_TRANSFER_OUT",
        symbol: "VXUS",
        units: 15.0,
        price: 60.0
      )
    )

    inbound = snaptrade_entry("int_asset_in_001")
    outbound = snaptrade_entry("int_asset_out_001")

    assert_not_nil inbound
    assert_not_nil outbound
    assert inbound.entryable.is_a?(Trade)
    assert outbound.entryable.is_a?(Trade)
    assert_equal BigDecimal("25.0"), inbound.entryable.qty
    assert_equal BigDecimal("-15.0"), outbound.entryable.qty
    assert_equal BigDecimal("0"), inbound.amount, "internal asset transfer in has zero cash flow"
    assert_equal BigDecimal("0"), outbound.amount, "internal asset transfer out has zero cash flow"
    assert_equal "Transfer", inbound.entryable.investment_activity_label
    assert_equal "Transfer", outbound.entryable.investment_activity_label
  end

  test "processes STOCK_MERGER as zero-cash trade preserving signed units" do
    process_activities(
      build_trade_activity(
        id: "merger_retire",
        type: "STOCK_MERGER",
        symbol: "AAPL",
        units: -100.0,
        price: nil,
        amount: nil
      ),
      build_trade_activity(
        id: "merger_receive",
        type: "STOCK_MERGER",
        symbol: "MSFT",
        units: 50.0,
        price: nil,
        amount: nil
      )
    )

    retire = snaptrade_entry("merger_retire")
    receive = snaptrade_entry("merger_receive")

    assert_not_nil retire
    assert_not_nil receive
    assert retire.entryable.is_a?(Trade)
    assert receive.entryable.is_a?(Trade)
    assert_equal BigDecimal("-100.0"), retire.entryable.qty, "negative units must retire acquired shares"
    assert_equal BigDecimal("50.0"), receive.entryable.qty, "positive units must add new shares"
    assert_equal BigDecimal("0"), retire.amount
    assert_equal BigDecimal("0"), receive.amount
    assert_equal "Other", retire.entryable.investment_activity_label
    assert_equal "Other", receive.entryable.investment_activity_label
  end

  test "processes STOCK_MERGER with cash-in-lieu or cash consideration preserving cash amount" do
    process_activities(
      build_trade_activity(
        id: "merger_cash_in_lieu",
        type: "STOCK_MERGER",
        symbol: "AAPL",
        units: -0.5,
        price: nil,
        amount: 45.00
      )
    )

    entry = snaptrade_entry("merger_cash_in_lieu")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    assert_equal BigDecimal("-0.5"), entry.entryable.qty
    assert_equal BigDecimal("-45.00"), entry.amount, "cash-in-lieu proceeds must be negative entry amount (money in)"
    assert_equal BigDecimal("90.00"), entry.entryable.price
  end

  test "processes STOCK_MERGER with cash-only payload as a Transaction" do
    process_activities(
      build_cash_activity(
        id: "merger_cash_only",
        type: "STOCK_MERGER",
        amount: 150.00,
        settlement_date: Date.current.to_s
      )
    )

    entry = snaptrade_entry("merger_cash_only")
    assert_not_nil entry
    assert entry.entryable.is_a?(Transaction)
    assert_equal BigDecimal("-150.00"), entry.amount, "cash merger payout must be negative entry amount (money in)"
    assert_equal "Other", entry.entryable.investment_activity_label
  end

  test "reclassifies pre-existing Transaction entry to Trade on resync without type collision error" do
    # Simulate an account that previously synced a SPLIT activity under the old cash-only code
    stale_entry = @account.entries.create!(
      external_id: "split_reclass_test",
      source: "snaptrade",
      amount: 304071.61,
      currency: "USD",
      date: Date.current,
      name: "DISTRIBUTION VANGUARD WORLD FD INF TECH ETF (VGT)",
      entryable: Transaction.new(investment_activity_label: "Other")
    )
    stale_entry_id = stale_entry.id

    assert stale_entry.entryable.is_a?(Transaction)

    # Re-sync with the updated ActivitiesProcessor
    process_activities(
      build_trade_activity(
        id: "split_reclass_test",
        type: "SPLIT",
        symbol: "VGT",
        units: 3010.014,
        price: 0.0,
        amount: 304071.61
      )
    )

    reclassified_entry = snaptrade_entry("split_reclass_test")
    assert_not_nil reclassified_entry
    assert_not_equal stale_entry_id, reclassified_entry.id, "stale entry should be replaced with reclassified entry"
    assert reclassified_entry.entryable.is_a?(Trade), "entry must be reclassified to Trade"
    assert_equal BigDecimal("3010.014"), reclassified_entry.entryable.qty
    assert_equal BigDecimal("0.0"), reclassified_entry.amount, "split trade must have zero cash amount"
    assert_equal BigDecimal("0.0"), reclassified_entry.entryable.price
    assert_nil snaptrade_debug_log("split_reclass_test", level: "error")
  end

  test "reclassifies pre-existing Trade entry to Transaction on resync without type collision error" do
    # Simulate an entry previously imported as a Trade (e.g. stock merger with units)
    security = Security.find_or_create_by!(ticker: "AAPL") { |s| s.name = "Apple Inc"; s.currency = "USD" }
    stale_entry = @account.entries.create!(
      external_id: "merger_reclass_test",
      source: "snaptrade",
      amount: 0.0,
      currency: "USD",
      date: Date.current,
      name: "STOCK_MERGER AAPL",
      entryable: Trade.new(security: security, qty: 10, price: 150.0, currency: "USD")
    )
    stale_entry_id = stale_entry.id

    assert stale_entry.entryable.is_a?(Trade)

    # Re-sync as a cash-only merger payout (0 units)
    process_activities(
      build_cash_activity(
        id: "merger_reclass_test",
        type: "STOCK_MERGER",
        amount: 500.00,
        settlement_date: Date.current.to_s
      )
    )

    reclassified_entry = snaptrade_entry("merger_reclass_test")
    assert_not_nil reclassified_entry
    assert_not_equal stale_entry_id, reclassified_entry.id, "stale trade entry should be replaced"
    assert reclassified_entry.entryable.is_a?(Transaction), "entry must be reclassified to Transaction"
    assert_equal BigDecimal("-500.00"), reclassified_entry.amount
    assert_nil snaptrade_debug_log("merger_reclass_test", level: "error")
  end

  test "skips reclassification and preserves existing entry when import_locked" do
    # When user manually locked an entry, resync must not destroy or reclassify it
    locked_entry = @account.entries.create!(
      external_id: "locked_split_test",
      source: "snaptrade",
      amount: 0.0,
      currency: "USD",
      date: Date.current,
      name: "DISTRIBUTION VGT (Manual Lock)",
      import_locked: true,
      entryable: Transaction.new(investment_activity_label: "Other")
    )
    original_id = locked_entry.id

    process_activities(
      build_trade_activity(
        id: "locked_split_test",
        type: "SPLIT",
        symbol: "VGT",
        units: 3010.014,
        price: 0.0,
        amount: 304071.61
      )
    )

    entry = snaptrade_entry("locked_split_test")
    assert_not_nil entry
    assert_equal original_id, entry.id, "locked entry ID must be preserved"
    assert entry.entryable.is_a?(Transaction), "locked entry must not be converted to Trade"
    assert_equal BigDecimal("0.0"), entry.amount

    log = snaptrade_debug_log("locked_split_test", level: "warn")
    assert_not_nil log
    assert_includes log.message, "Skipping reclassification of protected entry"
  end

  test "skips reclassification and preserves existing entry when user_modified" do
    user_entry = @account.entries.create!(
      external_id: "user_modified_split_test",
      source: "snaptrade",
      amount: 0.0,
      currency: "USD",
      date: Date.current,
      name: "Edited Split Entry",
      user_modified: true,
      entryable: Transaction.new(investment_activity_label: "Other")
    )
    original_id = user_entry.id

    process_activities(
      build_trade_activity(
        id: "user_modified_split_test",
        type: "SPLIT",
        symbol: "VGT",
        units: 100.0,
        price: 0.0,
        amount: 10000.00
      )
    )

    entry = snaptrade_entry("user_modified_split_test")
    assert_not_nil entry
    assert_equal original_id, entry.id, "user-modified entry ID must be preserved"
    assert entry.entryable.is_a?(Transaction), "user-modified entry must not be converted"

    log = snaptrade_debug_log("user_modified_split_test", level: "warn")
    assert_not_nil log
    assert_includes log.message, "Skipping reclassification of protected entry"
  end

  test "processes zero-amount trade types when price and amount are omitted" do
    process_activities(
      build_trade_activity(
        id: "opt_exp_long",
        type: "OPTIONEXPIRATION",
        symbol: "AAPL",
        units: -1.0,
        price: nil,
        amount: nil
      ),
      build_trade_activity(
        id: "opt_exp_short",
        type: "OPTIONEXPIRATION",
        symbol: "MSFT",
        units: 1.0,
        price: nil,
        amount: nil
      )
    )

    long_entry = snaptrade_entry("opt_exp_long")
    short_entry = snaptrade_entry("opt_exp_short")

    assert_not_nil long_entry, "zero-amount trade types must import even when price and amount are omitted"
    assert_not_nil short_entry
    assert long_entry.entryable.is_a?(Trade)
    assert short_entry.entryable.is_a?(Trade)
    assert_equal BigDecimal("-1.0"), long_entry.entryable.qty, "negative units must close out expired long contract"
    assert_equal BigDecimal("1.0"), short_entry.entryable.qty, "positive units must close out expired short contract"
    assert_equal BigDecimal("0"), long_entry.entryable.price
    assert_equal BigDecimal("0"), short_entry.entryable.price
    assert_equal BigDecimal("0"), long_entry.amount
    assert_equal BigDecimal("0"), short_entry.amount
    assert_equal "Other", long_entry.entryable.investment_activity_label
    assert_equal "Other", short_entry.entryable.investment_activity_label
  end

  test "processes share ADJUSTMENT as a zero-cash trade preserving signed units" do
    process_activities(
      build_trade_activity(
        id: "share_adj_add",
        type: "ADJUSTMENT",
        symbol: "VTI",
        units: 5.0,
        price: nil,
        amount: 500.00 # Notional value must not become cash flow
      ),
      build_trade_activity(
        id: "share_adj_remove",
        type: "ADJUSTMENT",
        symbol: "VTI",
        units: -3.0,
        price: nil,
        amount: -300.00
      )
    )

    add_entry = snaptrade_entry("share_adj_add")
    remove_entry = snaptrade_entry("share_adj_remove")

    assert_not_nil add_entry
    assert_not_nil remove_entry
    assert add_entry.entryable.is_a?(Trade), "ADJUSTMENT with units must be imported as a Trade"
    assert remove_entry.entryable.is_a?(Trade)

    assert_equal BigDecimal("5.0"), add_entry.entryable.qty, "positive units represents shares added"
    assert_equal BigDecimal("-3.0"), remove_entry.entryable.qty, "negative units represents shares removed"
    assert_equal BigDecimal("0"), add_entry.entryable.price
    assert_equal BigDecimal("0"), remove_entry.entryable.price
    assert_equal BigDecimal("0"), add_entry.amount
    assert_equal BigDecimal("0"), remove_entry.amount
    assert_equal "Other", add_entry.entryable.investment_activity_label
    assert_equal "Other", remove_entry.entryable.investment_activity_label
  end

  test "imports OTHER and JOURNAL share movements that carry no cash as zero-cash Transfer trades preserving signed units" do
    process_activities(
      # Shaped like a stock-plan vest: the shares arrive with price and amount both 0.0
      build_trade_activity(id: "other_shares_in", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0),
      build_trade_activity(id: "journal_shares_out", type: "JOURNAL", symbol: "RSUCO", units: -4.0, price: 25.0)
    )

    shares_in = snaptrade_entry("other_shares_in")
    shares_out = snaptrade_entry("journal_shares_out")

    assert_not_nil shares_in, "units with no cash are shares moving in"
    assert_not_nil shares_out, "negative units with no cash are shares moving out"
    assert shares_in.entryable.is_a?(Trade)
    assert shares_out.entryable.is_a?(Trade)
    assert_equal BigDecimal("10"), shares_in.entryable.qty
    assert_equal BigDecimal("-4"), shares_out.entryable.qty
    assert_equal BigDecimal("0"), shares_in.amount
    assert_equal BigDecimal("0"), shares_out.amount
    assert_equal BigDecimal("0"), shares_in.entryable.price
    assert_equal BigDecimal("25"), shares_out.entryable.price, "a reported price is kept"
    assert_equal "Transfer", shares_in.entryable.investment_activity_label, "shares that arrive at no known cost leave the cost basis unknown"
    assert_equal "Transfer", shares_out.entryable.investment_activity_label, "shares that leave without cash are not a sale"
  end

  test "resyncing an OTHER share movement updates its trade rather than adding another" do
    activity = build_trade_activity(id: "other_resync", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)
    process_activities(activity)
    first_import = snaptrade_entry("other_resync")
    assert_not_nil first_import

    assert_no_difference -> { @account.entries.count } do
      process_activities(activity)
    end

    entry = snaptrade_entry("other_resync")
    assert_equal first_import.id, entry.id
    assert_equal first_import.entryable_id, entry.entryable_id
    assert_equal BigDecimal("10"), entry.entryable.qty
    assert_equal BigDecimal("0"), entry.amount
  end

  test "keeps OTHER and JOURNAL rows that carry cash on the cash path, with or without units" do
    process_activities(
      build_trade_activity(id: "other_units_and_cash", type: "OTHER", symbol: "RSUCO", units: 5.0, price: 50.0, amount: -250.0),
      build_cash_activity(id: "journal_cash", type: "JOURNAL", amount: 100.0, settlement_date: Date.current.to_s)
    )

    with_units = snaptrade_entry("other_units_and_cash")
    cash_only = snaptrade_entry("journal_cash")

    assert with_units.entryable.is_a?(Transaction), "beside cash, what the units mean is unknown, so only the cash is booked"
    assert cash_only.entryable.is_a?(Transaction)
    assert_equal BigDecimal("-250"), with_units.amount
    assert_equal BigDecimal("100"), cash_only.amount
    assert_equal "Other", with_units.entryable.investment_activity_label
    assert_equal "Other", cash_only.entryable.investment_activity_label
  end

  test "skips OTHER and JOURNAL rows that carry neither units nor cash" do
    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_cash_activity(id: "other_no_units", type: "OTHER", amount: 0.0, settlement_date: Date.current.to_s),
        build_trade_activity(id: "journal_zero_units", type: "JOURNAL", symbol: "RSUCO", units: 0, price: 0.0)
      )
    end

    assert_nil snaptrade_debug_log("journal_zero_units"), "a row without units never reaches the trade path"
  end

  test "replaces a Transaction stored under the same id when the row arrives as a share movement" do
    stale_entry = @account.entries.create!(
      external_id: "other_reclass",
      source: "snaptrade",
      amount: 250.0,
      currency: "USD",
      date: Date.current,
      name: "OTHER RSUCO",
      entryable: Transaction.new(investment_activity_label: "Other")
    )

    process_activities(
      build_trade_activity(id: "other_reclass", type: "OTHER", symbol: "RSUCO", units: 5.0, price: 0.0, amount: 0.0)
    )

    entry = snaptrade_entry("other_reclass")
    assert_not_equal stale_entry.id, entry.id, "the stale transaction is replaced"
    assert entry.entryable.is_a?(Trade)
    assert_equal BigDecimal("5"), entry.entryable.qty
    assert_equal BigDecimal("0"), entry.amount
    assert_nil snaptrade_debug_log("other_reclass", category: "provider_sync_error", level: "error")
  end

  test "skips an OTHER share movement without a symbol and creates debug log" do
    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_trade_activity(id: "other_no_symbol", type: "OTHER", symbol: nil, units: 3.0, price: 0.0, amount: 0.0)
      )
    end

    assert_equal "missing_symbol", snaptrade_debug_log("other_no_symbol")&.metadata&.dig("reason")
  end

  test "imports TRANSFER rows that move shares without cash as Transfer trades signed by direction" do
    process_activities(
      build_trade_activity(id: "transfer_shares_in", type: "TRANSFER", symbol: "RSUCO", units: 10.0, price: 0.0),
      build_trade_activity(id: "transfer_shares_out", type: "TRANSFER", symbol: "RSUCO", units: -4.0, price: 0.0, amount: 0.0),
      build_trade_activity(id: "transfer_in_shares", type: "TRANSFER_IN", symbol: "RSUCO", units: 5.0, price: 0.0),
      build_trade_activity(id: "transfer_out_shares", type: "TRANSFER_OUT", symbol: "RSUCO", units: 3.0, price: 0.0)
    )

    expected = { "transfer_shares_in" => 10, "transfer_shares_out" => -4, "transfer_in_shares" => 5, "transfer_out_shares" => -3 }
    expected.each do |id, qty|
      entry = snaptrade_entry(id)
      assert entry&.entryable.is_a?(Trade), "#{id}: a transfer of shares with no cash moves shares"
      assert_equal BigDecimal(qty.to_s), entry.entryable.qty, id
      assert_equal BigDecimal("0"), entry.amount, id
      assert_equal "Transfer", entry.entryable.investment_activity_label, id
    end
  end

  test "does not import share movements that cancel each other out on the same day" do
    process_activities(
      build_trade_activity(id: "journal_out", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 110.0, amount: 0.0),
      build_trade_activity(id: "journal_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 110.0, amount: 0.0),
      build_trade_activity(id: "journal_in_later", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 110.0, amount: 0.0,
                           settlement_date: Date.yesterday.to_s),
      build_trade_activity(id: "journal_out_settles_later", type: "JOURNAL", symbol: "RSUCO", units: -7.0, price: 0.0, amount: 0.0,
                           settlement_date: Date.yesterday.to_s).merge("trade_date" => 2.days.ago.to_date.to_s),
      build_trade_activity(id: "journal_in_settles_later", type: "JOURNAL", symbol: "RSUCO", units: 7.0, price: 0.0, amount: 0.0,
                           settlement_date: Date.yesterday.to_s).merge("trade_date" => 2.days.ago.to_date.to_s)
    )

    assert_nil snaptrade_entry("journal_out"), "moved out and back in the same day, the shares never left"
    assert_nil snaptrade_entry("journal_in")
    assert_equal BigDecimal("100"), snaptrade_entry("journal_in_later")&.entryable&.qty, "a movement on another day is not a counterpart"
    assert_nil snaptrade_entry("journal_out_settles_later"), "legs with the same dates are a pair, though a leg out is booked on the later"
    assert_nil snaptrade_entry("journal_in_settles_later")
  end

  test "a row the share-movement matching cannot read does not stop the other rows" do
    process_activities(
      build_trade_activity(id: "odd_type", type: "JOURNAL", symbol: "RSUCO", units: 5.0, price: 0.0, amount: 0.0).merge("type" => 123),
      build_trade_activity(id: "journal_alone", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0, amount: 0.0)
    )

    assert_equal BigDecimal("100"), snaptrade_entry("journal_alone")&.entryable&.qty
  end

  test "share movements that cancel but for a float's rounding are not imported" do
    process_activities(
      build_trade_activity(id: "rounded_out", type: "JOURNAL", symbol: "RSUCO", units: -99.99999999999999, price: 0.0, amount: 0.0),
      build_trade_activity(id: "rounded_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0, amount: 0.0)
    )

    assert_nil snaptrade_entry("rounded_out")
    assert_nil snaptrade_entry("rounded_in")
  end

  test "share movements of one ticker on different exchanges do not cancel" do
    on_exchange = ->(activity, mic) { activity.tap { |a| a["symbol"] = a["symbol"].merge("exchange" => { "code" => mic, "mic_code" => mic }) } }

    process_activities(
      on_exchange.(build_trade_activity(id: "nyse_out", type: "JOURNAL", symbol: "DUAL", units: -30.0, price: 0.0, amount: 0.0), "XNYS"),
      on_exchange.(build_trade_activity(id: "tsx_in", type: "JOURNAL", symbol: "DUAL", units: 30.0, price: 0.0, amount: 0.0), "XTSE"),
      on_exchange.(build_trade_activity(id: "nyse_back_out", type: "JOURNAL", symbol: "DUAL", units: -5.0, price: 0.0, amount: 0.0), "XNYS"),
      on_exchange.(build_trade_activity(id: "nyse_back_in", type: "JOURNAL", symbol: "DUAL", units: 5.0, price: 0.0, amount: 0.0), "xnys")
    )

    assert_equal BigDecimal("-30"), snaptrade_entry("nyse_out")&.entryable&.qty, "one ticker on two exchanges can be two securities"
    assert_equal BigDecimal("30"), snaptrade_entry("tsx_in")&.entryable&.qty
    assert_nil snaptrade_entry("nyse_back_out"), "on the same exchange they still cancel"
    assert_nil snaptrade_entry("nyse_back_in")
  end

  test "share movements on the same trade date that settle on different days do not cancel" do
    process_activities(
      build_trade_activity(id: "settles_early_in", type: "JOURNAL", symbol: "RSUCO", units: 12.0, price: 0.0, amount: 0.0,
                           settlement_date: 2.days.ago.to_date.to_s).merge("trade_date" => 2.days.ago.to_date.to_s),
      build_trade_activity(id: "settles_late_out", type: "JOURNAL", symbol: "RSUCO", units: -12.0, price: 0.0, amount: 0.0,
                           settlement_date: Date.yesterday.to_s).merge("trade_date" => 2.days.ago.to_date.to_s)
    )

    assert_equal 2.days.ago.to_date, snaptrade_entry("settles_early_in")&.date, "booked on different days, the legs are not a pair"
    assert_equal Date.yesterday, snaptrade_entry("settles_late_out")&.date
  end

  test "share movements of one ticker cancel though their symbol data differs" do
    out_leg = build_trade_activity(id: "shape_out", type: "JOURNAL", symbol: "RSUCO", units: -40.0, price: 0.0, amount: 0.0)
    in_leg = build_trade_activity(id: "shape_in", type: "JOURNAL", symbol: "RSUCO", units: 40.0, price: 0.0, amount: 0.0)
    in_leg["symbol"] = in_leg["symbol"].merge("description" => "RSU Co (vested)", "id" => "sym-2")

    process_activities(out_leg, in_leg)

    assert_nil snaptrade_entry("shape_out")
    assert_nil snaptrade_entry("shape_in")
  end

  test "removes a share movement once the leg that cancels it arrives" do
    out_leg = build_trade_activity(id: "journal_late_pair_out", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 0.0)
    process_activities(out_leg)
    assert_not_nil snaptrade_entry("journal_late_pair_out")

    process_activities(out_leg, build_trade_activity(id: "journal_late_pair_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0))

    assert_nil snaptrade_entry("journal_late_pair_out")
    assert_nil snaptrade_entry("journal_late_pair_in")
  end

  test "imports the counterpart of a share movement protected from sync rather than cancelling the pair" do
    out_leg = build_trade_activity(id: "journal_kept_out", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 0.0)
    process_activities(out_leg)
    snaptrade_entry("journal_kept_out").mark_user_modified!

    process_activities(out_leg, build_trade_activity(id: "journal_kept_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 0.0))

    assert_equal BigDecimal("-100"), snaptrade_entry("journal_kept_out")&.entryable&.qty, "a protected entry is not removed"
    assert_equal BigDecimal("100"), snaptrade_entry("journal_kept_in")&.entryable&.qty, "so its counterpart is imported too, and together they move nothing"
  end

  test "leaves a share movement protected from sync as the user has it" do
    leg = build_trade_activity(id: "journal_edited", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 0.0)
    process_activities(leg)
    entry = snaptrade_entry("journal_edited")
    entry.entryable.update!(qty: -90)
    entry.update!(name: "Corrected by hand")
    entry.mark_user_modified!

    process_activities(leg)

    entry.reload
    assert_equal BigDecimal("-90"), entry.entryable.qty, "a sync does not import a protected movement again"
    assert_equal "Corrected by hand", entry.name
  end

  test "removes a share movement once its row reports no units and no cash" do
    process_activities(
      build_trade_activity(id: "journal_emptied", type: "JOURNAL", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0),
      build_trade_activity(id: "journal_emptied_kept", type: "JOURNAL", symbol: "RSUCO", units: 4.0, price: 0.0, amount: 0.0)
    )
    snaptrade_entry("journal_emptied_kept").mark_user_modified!

    process_activities(
      build_trade_activity(id: "journal_emptied", type: "JOURNAL", symbol: "RSUCO", units: 0.0, price: 0.0, amount: 0.0),
      build_trade_activity(id: "journal_emptied_kept", type: "JOURNAL", symbol: "RSUCO", units: 0.0, price: 0.0, amount: 0.0)
    )

    assert_nil snaptrade_entry("journal_emptied"), "the row moves nothing any more"
    assert_not_nil snaptrade_entry("journal_emptied_kept"), "a movement protected from sync stays"
  end

  test "removes a share movement once its row reports no units at all and no cash" do
    leg = build_trade_activity(id: "other_units_dropped", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)
    process_activities(leg)
    assert_not_nil snaptrade_entry("other_units_dropped")

    process_activities(leg.merge("units" => nil))

    assert_nil snaptrade_entry("other_units_dropped")
  end

  test "keeps a share movement whose row reports units it cannot read" do
    leg = build_trade_activity(id: "other_units_garbled", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)
    process_activities(leg)

    process_activities(leg.merge("units" => "pending"))

    assert_equal BigDecimal("10"), snaptrade_entry("other_units_garbled")&.entryable&.qty, "unreadable units are not a row emptied of them"
  end

  test "cancels a share movement against a leg that is not protected from sync" do
    kept_in = build_trade_activity(id: "transfer_in_kept", type: "TRANSFER_IN", symbol: "RSUCO", units: 100.0, price: 0.0)
    cancelled_in = build_trade_activity(id: "transfer_in_cancelled", type: "TRANSFER_IN", symbol: "RSUCO", units: 100.0, price: 0.0)
    process_activities(kept_in, cancelled_in)
    snaptrade_entry("transfer_in_kept").update!(excluded: true)

    process_activities(kept_in, cancelled_in, build_trade_activity(id: "transfer_out_cancelling", type: "TRANSFER_OUT", symbol: "RSUCO", units: 100.0, price: 0.0))

    assert_not_nil snaptrade_entry("transfer_in_kept")
    assert_nil snaptrade_entry("transfer_in_cancelled"), "the leg out pairs with the inbound leg that can go"
    assert_nil snaptrade_entry("transfer_out_cancelling")
  end

  test "removes a cash entry stored for a share movement that its counterpart cancels" do
    process_activities(
      build_trade_activity(id: "journal_was_cash", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 110.0, amount: -11000.0)
    )
    assert snaptrade_entry("journal_was_cash").entryable.is_a?(Transaction)

    process_activities(
      build_trade_activity(id: "journal_was_cash", type: "JOURNAL", symbol: "RSUCO", units: -100.0, price: 110.0, amount: 0.0),
      build_trade_activity(id: "journal_was_cash_in", type: "JOURNAL", symbol: "RSUCO", units: 100.0, price: 110.0, amount: 0.0)
    )

    assert_nil snaptrade_entry("journal_was_cash"), "the cash the row no longer reports goes too"
    assert_nil snaptrade_entry("journal_was_cash_in")
  end

  test "books the cash of an OTHER row whose net amount carries it" do
    process_activities(
      build_trade_activity(id: "other_net_cash", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 5.0, amount: 0.0).merge("net_amount" => 50.0)
    )

    entry = snaptrade_entry("other_net_cash")
    assert entry&.entryable.is_a?(Transaction), "a row that names cash anywhere is not a share movement"
    assert_equal BigDecimal("50"), entry.amount
  end

  test "records a debug entry the first time a row is imported as a share movement" do
    activity = build_trade_activity(id: "other_logged", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)

    process_activities(activity)
    process_activities(activity)

    logs = DebugLogEntry.where(provider_key: "snaptrade", level: "info").select { |log| log.metadata["activity_id"] == "other_logged" }
    assert_equal 1, logs.size, "logged once, not on every sync"
    assert_equal "share_movement", logs.first.metadata["reason"]
    assert_equal "10.0", logs.first.metadata["quantity"]
    assert_equal "RSUCO", logs.first.metadata["ticker"]
  end

  test "dates a share movement in by the earlier of its trade and settlement dates, and one out by the later" do
    process_activities(
      build_trade_activity(id: "other_settles_late", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0,
                           settlement_date: 1.day.ago.to_date.to_s).merge("trade_date" => 3.days.ago.to_date.to_s),
      build_trade_activity(id: "other_settles_early", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0,
                           settlement_date: 5.days.ago.to_date.to_s).merge("trade_date" => 2.days.ago.to_date.to_s),
      build_trade_activity(id: "transfer_out_settles_late", type: "TRANSFER_OUT", symbol: "RSUCO", units: 4.0, price: 0.0,
                           settlement_date: 2.days.ago.to_date.to_s).merge("trade_date" => 4.days.ago.to_date.to_s),
      build_trade_activity(id: "other_out_settles_early", type: "OTHER", symbol: "RSUCO", units: -3.0, price: 0.0, amount: 0.0,
                           settlement_date: 6.days.ago.to_date.to_s).merge("trade_date" => 4.days.ago.to_date.to_s),
      build_trade_activity(id: "sell_settles_late", type: "SELL", symbol: "RSUCO", units: -10.0, price: 100.0, amount: 1000.0,
                           settlement_date: 1.day.ago.to_date.to_s).merge("trade_date" => 3.days.ago.to_date.to_s)
    )

    assert_equal 3.days.ago.to_date, snaptrade_entry("other_settles_late").date, "shares are never sold before they arrive"
    assert_equal 5.days.ago.to_date, snaptrade_entry("other_settles_early").date
    assert_equal 2.days.ago.to_date, snaptrade_entry("transfer_out_settles_late").date, "nor moved out before the buy that delivered them"
    assert_equal 4.days.ago.to_date, snaptrade_entry("other_out_settles_early").date
    assert_equal 1.day.ago.to_date, snaptrade_entry("sell_settles_late").date, "a trade keeps its settlement date"
  end

  test "ignores cash activities with zero or nil amount" do
    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_cash_activity(id: "zero_cash_001", type: "DIVIDEND", amount: 0.0, settlement_date: Date.current.to_s),
        build_cash_activity(id: "nil_cash_001", type: "CONTRIBUTION", amount: nil, settlement_date: Date.current.to_s)
      )
    end
  end

  test "imports an unmapped activity type as Other and creates debug log" do
    process_activities(
      build_cash_activity(id: "unknown_001", type: "SOME_NEW_TYPE", amount: 100.00, settlement_date: Date.current.to_s)
    )

    entry = snaptrade_entry("unknown_001")
    assert_not_nil entry, "an unmapped activity type is still imported"
    assert_equal "Other", entry.entryable.investment_activity_label

    log = DebugLogEntry.where(provider_key: "snaptrade", category: "provider_sync", level: "warn")
                       .find { |e| e.metadata["activity_type"] == "SOME_NEW_TYPE" }
    assert_not_nil log, "an unmapped activity type must be recorded in /settings/debug"
    assert_equal @family, log.family
    assert_equal @snaptrade_account.account_provider, log.account_provider
  end

  test "skips the trade and creates debug log when symbol is missing" do
    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_trade_activity(id: "skip_no_symbol", type: "BUY", symbol: nil, units: 1, price: 10.00, amount: -10.00)
      )
    end

    assert_equal "missing_symbol", snaptrade_debug_log("skip_no_symbol")&.metadata&.dig("reason")
  end

  test "skips the trade and creates debug log when quantity is missing" do
    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_trade_activity(id: "skip_no_quantity", type: "BUY", symbol: "AAPL", units: nil, price: 10.00, amount: -10.00)
      )
    end

    assert_equal "missing_quantity", snaptrade_debug_log("skip_no_quantity")&.metadata&.dig("reason")
  end

  test "skips the trade and creates debug log when amount and price are both missing" do
    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_trade_activity(id: "skip_no_amount", type: "BUY", symbol: "AAPL", units: 5, price: nil)
      )
    end

    log = snaptrade_debug_log("skip_no_amount")
    assert_equal "missing_amount", log&.metadata&.dig("reason")
    assert_equal @family, log.family
    assert_equal @snaptrade_account.account_provider, log.account_provider
  end

  test "skips the trade and creates debug log when security is unresolvable" do
    SnaptradeAccount::ActivitiesProcessor.any_instance.stubs(:resolve_security).returns(nil)

    assert_no_difference -> { @account.entries.count } do
      process_activities(
        build_trade_activity(id: "skip_unresolved", type: "BUY", symbol: "ZZZZ", units: 1, price: 10.00, amount: -10.00)
      )
    end

    log = snaptrade_debug_log("skip_unresolved")
    assert_equal "unresolved_security", log&.metadata&.dig("reason")
    assert_equal "ZZZZ", log&.metadata&.dig("ticker")
  end

  test "skips an activity that fails to import, keeps processing, and creates debug log" do
    Account::ProviderImportAdapter.any_instance.stubs(:import_trade).raises(StandardError, "boom")

    process_activities(
      build_trade_activity(id: "trade_fails", type: "BUY", symbol: "AAPL", units: 1, price: 10.00, amount: -10.00),
      build_cash_activity(id: "div_after_failure", type: "DIVIDEND", amount: 5.00, settlement_date: Date.current.to_s)
    )

    assert_nil snaptrade_entry("trade_fails")
    assert_not_nil snaptrade_entry("div_after_failure"), "later activities are still processed"

    log = snaptrade_debug_log("trade_fails", category: "provider_sync_error", level: "error")
    assert_not_nil log, "a failed activity must be recorded in /settings/debug"
    assert_equal "BUY", log.metadata["activity_type"]
    assert_includes log.message, "boom"
  end

  test "skips activities without external_id" do
    @snaptrade_account.update!(raw_activities_payload: [
      build_cash_activity(
        id: nil,
        type: "DIVIDEND",
        amount: 50.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    # No entry should be created with snaptrade source
    assert_equal 0, @account.entries.where(source: "snaptrade").count
  end

  test "skips processing when no linked account" do
    # Remove the account provider link
    @snaptrade_account.account_provider&.destroy
    @snaptrade_account.reload

    @snaptrade_account.update!(raw_activities_payload: [
      build_trade_activity(
        id: "trade_orphan",
        type: "BUY",
        symbol: "AAPL",
        units: 10,
        price: 150.00,
        settlement_date: Date.current.to_s
      )
    ])

    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)
    processor.process

    # No entries should be created with this external_id
    assert_equal 0, Entry.where(external_id: "trade_orphan").count
  end

  test "skips processing a share movement when no linked account" do
    @snaptrade_account.account_provider&.destroy
    @snaptrade_account.reload
    @snaptrade_account.update!(raw_activities_payload: [
      build_trade_activity(id: "movement_orphan", type: "OTHER", symbol: "RSUCO", units: 10.0, price: 0.0, amount: 0.0)
    ])

    assert_nothing_raised { SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account).process }
    assert_equal 0, Entry.where(external_id: "movement_orphan").count
  end

  test "a trade resolves to the security the account already holds when its ticker has duplicate rows" do
    held = Security.create!(ticker: "DUPT", name: "Held row")
    Security.create!(ticker: "DUPT", name: "Priced row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
    @account.holdings.create!(
      security: held, date: 1.day.ago.to_date, qty: 10, price: 100, amount: 1000, currency: "USD",
      account_provider_id: @snaptrade_account.account_provider&.id
    )
    held.update!(name: "Held row (renamed)")

    process_activities(build_trade_activity(id: "dup_trade", type: "BUY", symbol: "DUPT", units: 1, price: 100))

    assert_equal held, snaptrade_entry("dup_trade").entryable.security
  end

  # A remap moves the position's trades to the row the user chose, so a new
  # trade must land there too, not on the provider's original row.
  test "a trade for a remapped position lands on the row the user chose" do
    original = Security.create!(ticker: "DUPT2", name: "SnapTrade row")
    listed = Security.create!(ticker: "DUPT2", name: "Listed row", exchange_operating_mic: "XNYS", price_provider: "yahoo_finance")
    @account.holdings.create!(
      security: original, date: 1.day.ago.to_date, qty: 10, price: 100, amount: 1000, currency: "USD",
      account_provider_id: @snaptrade_account.account_provider&.id
    ).remap_security!(listed)

    process_activities(build_trade_activity(id: "remapped_trade", type: "BUY", symbol: "DUPT2", units: 1, price: 100))

    assert_equal listed, snaptrade_entry("remapped_trade").entryable.security
  end

  # Modeled on real Fidelity option buy activity (TQQQ call) where symbol is nil
  test "processes option buy trade when symbol is nil and option_symbol is present" do
    process_activities(
      build_option_activity(
        id: "opt_buy_001",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: 0.57,
        amount: -114.05,
        fee: 0.05,
        underlying_symbol: "TQQQ"
      )
    )

    entry = snaptrade_entry("opt_buy_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)

    trade = entry.entryable
    assert_equal 2.0, trade.qty
    assert_equal 57.0, trade.price.to_f
    assert_equal 114.05, entry.amount.to_f
    assert_equal "Buy", trade.investment_activity_label

    security = trade.security
    assert_equal "TQQQ  260220C00051000", security.ticker
    assert_equal "TQQQ $51 CALL (2026-02-20)", security.name
    assert_equal "XNAS", security.exchange_mic
    assert_equal "US", security.country_code
  end

  # Modeled on real Fidelity option sell activity (NKE call) where symbol is nil
  test "processes option sell trade when symbol is nil and option_symbol is present" do
    process_activities(
      build_option_activity(
        id: "opt_sell_001",
        type: "SELL",
        ticker: "NKE   261218C00050000",
        option_type: "CALL",
        strike_price: 50.0,
        expiration_date: "2026-12-18",
        units: -6.0,
        price: 30.70,
        amount: 18415.94,
        fee: 4.06,
        underlying_symbol: "NKE"
      )
    )

    entry = snaptrade_entry("opt_sell_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)

    trade = entry.entryable
    assert_equal(-6.0, trade.qty)
    assert_equal 3070.0, trade.price.to_f
    assert_equal(-18415.94, entry.amount.to_f)
    assert_equal "Sell", trade.investment_activity_label

    security = trade.security
    assert_equal "NKE   261218C00050000", security.ticker
    assert_equal "NKE $50 CALL (2026-12-18)", security.name
  end

  # Modeled on real Robinhood option sell activity (Unity call) where symbol contains the underlying equity
  test "prioritizes option_symbol over underlying equity symbol for option trades" do
    process_activities(
      build_option_activity(
        id: "opt_robinhood_001",
        type: "SELL",
        symbol: { "symbol" => "U", "description" => "Unity Software Inc." },
        ticker: "U     270115C00015000",
        option_type: "CALL",
        strike_price: 15.0,
        expiration_date: "2027-01-15",
        units: -5.0,
        price: 14.0,
        amount: 7000.0,
        underlying_symbol: "U"
      )
    )

    entry = snaptrade_entry("opt_robinhood_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)

    trade = entry.entryable
    assert_equal "U     270115C00015000", trade.security.ticker
    assert_equal "U $15 CALL (2027-01-15)", trade.security.name
    assert_not_equal "U", trade.security.ticker
    assert_equal BigDecimal("1400.0"), trade.price
    assert_equal BigDecimal("-7000.0"), entry.amount
  end

  # Modeled on real Fidelity option exercise activity (JNJ call exercise)
  test "processes option exercise trade preserving negative quantity" do
    process_activities(
      build_option_activity(
        id: "opt_exercise_001",
        type: "OPTIONEXERCISE",
        ticker: "JNJ   260116C00125000",
        option_type: "CALL",
        strike_price: 125.0,
        expiration_date: "2026-01-16",
        units: -1.0,
        price: 0.0,
        amount: -5415.0,
        underlying_symbol: "JNJ"
      )
    )

    entry = snaptrade_entry("opt_exercise_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)

    trade = entry.entryable
    assert_equal(-1.0, trade.qty)
    assert_equal "Other", trade.investment_activity_label
    assert_equal "JNJ   260116C00125000", trade.security.ticker
  end

  # Modeled on real Robinhood option expiration activity (Allbirds call expiration)
  test "processes option expiration trade with zero amount" do
    process_activities(
      build_option_activity(
        id: "opt_expire_001",
        type: "OPTIONEXPIRATION",
        ticker: "BIRD  250117C00000500",
        option_type: "CALL",
        strike_price: 0.5,
        expiration_date: "2025-01-17",
        units: -80.0,
        price: 0.0,
        amount: 0.0,
        underlying_symbol: "BIRD"
      )
    )

    entry = snaptrade_entry("opt_expire_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)

    trade = entry.entryable
    assert_equal(-80.0, trade.qty)
    assert_equal 0.0, entry.amount.to_f
    assert_equal "BIRD  250117C00000500", trade.security.ticker
    assert_equal "BIRD $0.5 CALL (2025-01-17)", trade.security.name
  end

  # Modeled on real Fidelity option transfer activity (JNJ call transfer)
  test "falls back to option ticker for transaction description in cash activities" do
    process_activities(
      {
        "id" => "opt_transfer_001",
        "type" => "TRANSFER",
        "amount" => 5435.0,
        "units" => 1.0,
        "price" => 0.0,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" },
        "symbol" => nil,
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => "JNJ   260116C00125000",
          "option_type" => "CALL",
          "strike_price" => 125.0,
          "expiration_date" => "2026-01-16"
        }
      }
    )

    entry = snaptrade_entry("opt_transfer_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Transaction)
    assert_equal "Transfer - JNJ   260116C00125000", entry.name
  end

  # Modeled on Robinhood option transfer activity where underlying equity is in symbol and option ticker is in option_symbol
  test "prefers option ticker over underlying symbol for transaction description in cash activities" do
    process_activities(
      {
        "id" => "opt_transfer_with_underlying_001",
        "type" => "TRANSFER",
        "amount" => 1500.0,
        "units" => 1.0,
        "price" => 0.0,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" },
        "symbol" => {
          "symbol" => "U",
          "description" => "Unity Software Inc."
        },
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => "U     270115C00015000",
          "option_type" => "CALL",
          "strike_price" => 15.0,
          "expiration_date" => "2027-01-15"
        }
      }
    )

    entry = snaptrade_entry("opt_transfer_with_underlying_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Transaction)
    assert_equal "Transfer - U     270115C00015000", entry.name
  end

  # Modeled on SnapTrade payload with bare string underlying_symbol
  test "processes option trade when underlying_symbol is a bare string instead of a hash" do
    process_activities(
      {
        "id" => "opt_bare_underlying_001",
        "type" => "BUY",
        "units" => 2.0,
        "price" => 0.57,
        "amount" => -114.05,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" },
        "symbol" => nil,
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => "TQQQ  260220C00051000",
          "option_type" => "CALL",
          "strike_price" => 51.0,
          "expiration_date" => "2026-02-20",
          "underlying_symbol" => "TQQQ"
        }
      }
    )

    entry = snaptrade_entry("opt_bare_underlying_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    assert_equal "TQQQ  260220C00051000", entry.entryable.security.ticker
    assert_equal "TQQQ $51 CALL (2026-02-20)", entry.entryable.security.name
    assert_equal BigDecimal("57.0"), entry.entryable.price
  end

  test "option_ticker_and_data extracts ticker and data or returns nil when absent or malformed" do
    processor = SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account)

    ticker, data = processor.send(:option_ticker_and_data, { "option_symbol" => { "ticker" => "AAPL  260116C00200000" } })
    assert_equal "AAPL  260116C00200000", ticker
    assert_equal "AAPL  260116C00200000", data[:ticker]

    ticker, = processor.send(:option_ticker_and_data, { option_symbol: { ticker: "AAPL  260116C00200000" } })
    assert_equal "AAPL  260116C00200000", ticker

    ticker, data = processor.send(:option_ticker_and_data, { "option_symbol" => nil })
    assert_nil ticker
    assert_nil data

    ticker, data = processor.send(:option_ticker_and_data, { "option_symbol" => "AAPL" })
    assert_nil ticker
    assert_nil data

    ticker, data = processor.send(:option_ticker_and_data, { "option_symbol" => { "ticker" => "" } })
    assert_nil ticker
    assert_nil data
  end

  test "processes mini-option trade with full payload when is_mini_option is true" do
    process_activities(
      {
        "id" => "mini_opt_trade_001",
        "type" => "BUY",
        "units" => 3.0,
        "price" => 1.25,
        "amount" => -37.50,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" },
        "symbol" => {
          "symbol" => "AAPL",
          "description" => "Apple Inc.",
          "currency" => { "code" => "USD" },
          "exchange" => { "mic_code" => "XNAS" }
        },
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => "AAPL7 260116C00200000",
          "option_type" => "CALL",
          "strike_price" => 200.0,
          "expiration_date" => "2026-01-16",
          "is_mini_option" => true,
          "underlying_symbol" => {
            "symbol" => "AAPL",
            "currency" => { "code" => "USD" },
            "exchange" => { "mic_code" => "XNAS" }
          }
        }
      }
    )

    entry = snaptrade_entry("mini_opt_trade_001")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    assert_equal "AAPL7 260116C00200000", entry.entryable.security.ticker
    assert_equal "AAPL $200 CALL (2026-01-16)", entry.entryable.security.name
    assert_equal BigDecimal("3.0"), entry.entryable.qty
    assert_equal BigDecimal("12.5"), entry.entryable.price
    assert_equal BigDecimal("37.50"), entry.amount
  end

  # Modeled on SnapTrade option payload where underlying symbol is omitted
  test "falls back to raw ticker when option symbol lacks underlying symbol details" do
    process_activities(
      {
        "id" => "opt_bare_001",
        "type" => "BUY",
        "units" => 1.0,
        "price" => 5.0,
        "amount" => -500.0,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" },
        "symbol" => nil,
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => "SPY   250620P00500000",
          "option_type" => "PUT",
          "strike_price" => 500.0,
          "expiration_date" => "2025-06-20",
          "is_mini_option" => false,
          "underlying_symbol" => nil
        }
      }
    )

    entry = snaptrade_entry("opt_bare_001")
    assert_not_nil entry
    assert_equal "SPY   250620P00500000", entry.entryable.security.ticker
    assert_equal "SPY   250620P00500000", entry.entryable.security.name
    assert_equal BigDecimal("500.0"), entry.entryable.price
  end

  test "retains underlying exchange and currency metadata when option_symbol lacks underlying_symbol" do
    process_activities(
      {
        "id" => "opt_fallback_meta_001",
        "type" => "BUY",
        "units" => 2.0,
        "price" => 0.57,
        "amount" => -114.05,
        "settlement_date" => Date.current.to_s,
        "symbol" => {
          "symbol" => "TQQQ",
          "description" => "ProShares UltraPro QQQ",
          "currency" => { "code" => "USD" },
          "exchange" => { "mic_code" => "XNAS" }
        },
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => "TQQQ  260220C00051000",
          "option_type" => "CALL",
          "strike_price" => 51.0,
          "expiration_date" => "2026-02-20",
          "is_mini_option" => false
        }
      }
    )

    entry = snaptrade_entry("opt_fallback_meta_001")
    assert_not_nil entry
    security = entry.entryable.security
    assert_equal "TQQQ  260220C00051000", security.ticker
    assert_equal "TQQQ $51 CALL (2026-02-20)", security.name
    assert_equal "XNAS", security.exchange_mic
    assert_equal "US", security.country_code
  end

  # Modeled on official SnapTrade getAccountActivities documentation payload
  test "processes option trade modeled on official SnapTrade API documentation payload" do
    process_activities(
      {
        "id" => "2f7dc9b3-5c33-4668-3440-2b31e056ebe6",
        "symbol" => {
          "id" => "2bcd7cc3-e922-4976-bce1-9858296801c3",
          "symbol" => "VAB.TO",
          "raw_symbol" => "VAB",
          "description" => "VANGUARD CDN AGGREGATE BOND INDEX ETF",
          "currency" => {
            "id" => "87b24961-b51e-4db8-9226-f198f6518a89",
            "code" => "USD",
            "name" => "US Dollar"
          },
          "exchange" => {
            "id" => "2bcd7cc3-e922-4976-bce1-9858296801c3",
            "code" => "TSX",
            "mic_code" => "XTSE",
            "name" => "Toronto Stock Exchange"
          },
          "type" => {
            "id" => "2bcd7cc3-e922-4976-bce1-9858296801c3",
            "code" => "cs",
            "description" => "Common Stock"
          }
        },
        "option_symbol" => {
          "id" => "2bcd7cc3-e922-4976-bce1-9858296801c3",
          "ticker" => "AAPL  261218C00240000",
          "option_type" => "CALL",
          "strike_price" => 240,
          "expiration_date" => "2026-12-18T00:00:00.000Z",
          "is_mini_option" => false,
          "underlying_symbol" => {
            "id" => "2bcd7cc3-e922-4976-bce1-9858296801c3",
            "symbol" => "SPY",
            "raw_symbol" => "VAB",
            "description" => "SPDR S&P 500 ETF Trust",
            "currency" => {
              "id" => "87b24961-b51e-4db8-9226-f198f6518a89",
              "code" => "USD",
              "name" => "US Dollar"
            },
            "exchange" => {
              "id" => "2bcd7cc3-e922-4976-bce1-9858296801c3",
              "code" => "ARCX",
              "mic_code" => "ARCA",
              "name" => "NYSE ARCA"
            }
          }
        },
        "price" => 0.4,
        "units" => 5.2,
        "amount" => 263.82,
        "currency" => {
          "id" => "87b24961-b51e-4db8-9226-f198f6518a89",
          "code" => "USD",
          "name" => "US Dollar"
        },
        "type" => "BUY",
        "option_type" => "BUY_TO_OPEN",
        "description" => "WALT DISNEY UNIT DIST ON 21 SHS REC 12/31/21 PAY 01/06/22",
        "trade_date" => "2024-03-22T16:27:55.000Z",
        "settlement_date" => "2024-03-26T00:00:00.000Z",
        "fee" => 0,
        "institution" => "Robinhood"
      }
    )

    entry = snaptrade_entry("2f7dc9b3-5c33-4668-3440-2b31e056ebe6")
    assert_not_nil entry
    assert entry.entryable.is_a?(Trade)
    security = entry.entryable.security
    assert_equal "AAPL  261218C00240000", security.ticker
    assert_equal "SPY $240 CALL (2026-12-18)", security.name
    assert_equal "ARCA", security.exchange_mic
    assert_equal "US", security.country_code
    assert_equal BigDecimal("5.2"), entry.entryable.qty
    assert_equal BigDecimal("40.0"), entry.entryable.price
    assert_equal BigDecimal("263.82"), entry.amount
  end

  # Modeled on SnapTrade payload with generic "COMMON STOCK" description (preserves 5-letter ticker case)
  test "preserves raw ticker without titleize when description is generic type" do
    process_activities(
      {
        "id" => "trade_generic_type_001",
        "type" => "BUY",
        "units" => 10.0,
        "price" => 150.0,
        "amount" => -1500.0,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" },
        "symbol" => {
          "symbol" => "GOOGL",
          "description" => "COMMON STOCK"
        }
      }
    )

    entry = snaptrade_entry("trade_generic_type_001")
    assert_not_nil entry
    assert_equal "GOOGL", entry.entryable.security.ticker
    assert_equal "GOOGL", entry.entryable.security.name
  end

  # Modeled on Robinhood resync: an option trade previously mis-imported as common stock
  test "updates pre-existing misclassified trade to option contract on resync without error" do
    equity_sec = Security.find_or_create_by!(ticker: "U") { |s| s.name = "Unity Software Inc." }
    pre_existing_entry = @account.entries.create!(
      external_id: "opt_resync_test_001",
      source: "snaptrade",
      amount: BigDecimal("-7000.0"),
      currency: "USD",
      date: Date.current,
      name: "sell 5.000 U call",
      entryable: Trade.new(security: equity_sec, qty: -5.0, price: 14.0, currency: "USD", investment_activity_label: "Sell")
    )
    entry_id = pre_existing_entry.id

    assert_equal "U", pre_existing_entry.entryable.security.ticker

    process_activities(
      build_option_activity(
        id: "opt_resync_test_001",
        type: "SELL",
        symbol: { "symbol" => "U", "description" => "Unity Software Inc." },
        ticker: "U     270115C00015000",
        option_type: "CALL",
        strike_price: 15.0,
        expiration_date: "2027-01-15",
        units: -5.0,
        price: 14.0,
        amount: 7000.0,
        underlying_symbol: "U"
      )
    )

    updated_entry = snaptrade_entry("opt_resync_test_001")
    assert_not_nil updated_entry
    assert_equal entry_id, updated_entry.id, "Existing entry should be updated in-place"
    assert_equal "U     270115C00015000", updated_entry.entryable.security.ticker
    assert_equal "U $15 CALL (2027-01-15)", updated_entry.entryable.security.name
    assert_equal BigDecimal("1400.0"), updated_entry.entryable.price
    assert_nil snaptrade_debug_log("opt_resync_test_001", level: "error")
  end

  # Modeled on resync where an option activity was previously imported as a cash Transaction
  test "reclassifies pre-existing Transaction entry to Trade on option resync without collision error" do
    stale_entry = @account.entries.create!(
      external_id: "opt_txn_reclass_001",
      source: "snaptrade",
      amount: 114.05,
      currency: "USD",
      date: Date.current,
      name: "OPTION BUY TQQQ",
      entryable: Transaction.new(investment_activity_label: "Other")
    )
    stale_id = stale_entry.id

    process_activities(
      build_option_activity(
        id: "opt_txn_reclass_001",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: 0.57,
        amount: -114.05,
        underlying_symbol: "TQQQ"
      )
    )

    reclassified_entry = snaptrade_entry("opt_txn_reclass_001")
    assert_not_nil reclassified_entry
    assert_not_equal stale_id, reclassified_entry.id, "Stale Transaction should be replaced by Trade"
    assert reclassified_entry.entryable.is_a?(Trade)
    assert_equal "TQQQ  260220C00051000", reclassified_entry.entryable.security.ticker
    assert_equal BigDecimal("57.0"), reclassified_entry.entryable.price
    assert_nil snaptrade_debug_log("opt_txn_reclass_001", level: "error")
  end

  test "skips reclassifying pre-existing option Transaction when import_locked" do
    locked_entry = @account.entries.create!(
      external_id: "opt_locked_reclass_001",
      source: "snaptrade",
      amount: 114.05,
      currency: "USD",
      date: Date.current,
      name: "OPTION BUY TQQQ (Manual Lock)",
      import_locked: true,
      entryable: Transaction.new(investment_activity_label: "Other")
    )
    original_id = locked_entry.id

    process_activities(
      build_option_activity(
        id: "opt_locked_reclass_001",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: 0.57,
        amount: -114.05,
        underlying_symbol: "TQQQ"
      )
    )

    entry = snaptrade_entry("opt_locked_reclass_001")
    assert_not_nil entry
    assert_equal original_id, entry.id, "locked entry ID must be preserved"
    assert entry.entryable.is_a?(Transaction), "locked entry must not be converted to Trade"
    assert_equal BigDecimal("114.05"), entry.amount

    log = snaptrade_debug_log("opt_locked_reclass_001", level: "warn")
    assert_not_nil log
    assert_includes log.message, "Skipping reclassification of protected entry"
  end

  # Synthetic edge case: option activities where amount is omitted (all real k8s activities include amount)
  test "derives option trade amount from contract-normalized price and fee when amount is omitted" do
    process_activities(
      build_option_activity(
        id: "opt_missing_amt_buy",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: 0.57,
        amount: nil,
        fee: 0.05
      ),
      build_option_activity(
        id: "opt_missing_amt_sell",
        type: "SELL",
        ticker: "NKE   261218C00050000",
        option_type: "CALL",
        strike_price: 50.0,
        expiration_date: "2026-12-18",
        units: 6.0,
        price: 30.70,
        amount: nil,
        fee: 4.06
      ),
      build_option_activity(
        id: "opt_missing_amt_mini",
        type: "BUY",
        ticker: "AAPL7 260116C00200000",
        option_type: "CALL",
        strike_price: 200.0,
        expiration_date: "2026-01-16",
        units: 3.0,
        price: 1.25,
        amount: nil,
        fee: 0.50,
        is_mini_option: true
      )
    )

    buy_entry = snaptrade_entry("opt_missing_amt_buy")
    assert_equal BigDecimal("2.0"), buy_entry.entryable.qty
    assert_equal BigDecimal("57.0"), buy_entry.entryable.price
    assert_equal BigDecimal("114.05"), buy_entry.amount

    sell_entry = snaptrade_entry("opt_missing_amt_sell")
    assert_equal BigDecimal("-6.0"), sell_entry.entryable.qty
    assert_equal BigDecimal("3070.0"), sell_entry.entryable.price
    assert_equal BigDecimal("-18415.94"), sell_entry.amount

    mini_entry = snaptrade_entry("opt_missing_amt_mini")
    assert_equal BigDecimal("3.0"), mini_entry.entryable.qty
    assert_equal BigDecimal("12.5"), mini_entry.entryable.price
    assert_equal BigDecimal("38.0"), mini_entry.amount
  end

  # Synthetic edge case: option activities where price is omitted (all real k8s activities include price)
  test "derives per-contract option trade price from amount, quantity, and fee when price is omitted" do
    process_activities(
      build_option_activity(
        id: "opt_missing_price_buy",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: nil,
        amount: -114.05,
        fee: 0.05
      ),
      build_option_activity(
        id: "opt_missing_price_sell",
        type: "SELL",
        ticker: "NKE   261218C00050000",
        option_type: "CALL",
        strike_price: 50.0,
        expiration_date: "2026-12-18",
        units: -6.0,
        price: nil,
        amount: 18415.94,
        fee: 4.06
      ),
      build_option_activity(
        id: "opt_missing_price_mini",
        type: "BUY",
        ticker: "AAPL7 260116C00200000",
        option_type: "CALL",
        strike_price: 200.0,
        expiration_date: "2026-01-16",
        units: 3.0,
        price: nil,
        amount: -37.50,
        is_mini_option: true
      )
    )

    buy_entry = snaptrade_entry("opt_missing_price_buy")
    assert_equal BigDecimal("2.0"), buy_entry.entryable.qty
    assert_equal BigDecimal("57.0"), buy_entry.entryable.price
    assert_equal BigDecimal("114.05"), buy_entry.amount

    sell_entry = snaptrade_entry("opt_missing_price_sell")
    assert_equal BigDecimal("-6.0"), sell_entry.entryable.qty
    assert_equal BigDecimal("3070.0"), sell_entry.entryable.price
    assert_equal BigDecimal("-18415.94"), sell_entry.amount

    mini_entry = snaptrade_entry("opt_missing_price_mini")
    assert_equal BigDecimal("3.0"), mini_entry.entryable.qty
    assert_equal BigDecimal("12.5"), mini_entry.entryable.price
    assert_equal BigDecimal("37.50"), mini_entry.amount
  end

  # Modeled on real Fidelity option buy activity (TQQQ call) materialized through Holding::Materializer
  test "materializes standard option holdings and calculated cost basis at per-contract value" do
    purchase_date = 2.days.ago.to_date

    process_activities(
      build_option_activity(
        id: "opt_mat_std_001",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: 0.57,
        amount: -114.05,
        fee: 0.05,
        settlement_date: purchase_date.to_s
      )
    )

    security = Security.find_by!(ticker: "TQQQ  260220C00051000")
    Holding::Materializer.new(@account, strategy: :forward).materialize_holdings

    purchase_holding = @account.holdings.find_by!(security: security, date: purchase_date)
    current_holding = @account.holdings.find_by!(security: security, date: Date.current)

    assert_equal BigDecimal("2.0"), purchase_holding.qty
    assert_equal BigDecimal("57.0"), purchase_holding.price
    assert_equal BigDecimal("114.0"), purchase_holding.amount
    assert_equal BigDecimal("57.025"), purchase_holding.cost_basis
    assert_equal "calculated", purchase_holding.cost_basis_source
    assert_equal Money.new(57.025, "USD"), purchase_holding.avg_cost

    assert_equal BigDecimal("2.0"), current_holding.qty
    assert_equal BigDecimal("57.0"), current_holding.price
    assert_equal BigDecimal("114.0"), current_holding.amount
    assert_equal BigDecimal("57.025"), current_holding.cost_basis
    assert_equal Money.new(57.025, "USD"), current_holding.avg_cost

    # Also verify reverse materialization when current snapshot is present
    Holding::Materializer.new(@account, strategy: :reverse).materialize_holdings

    reverse_purchase_holding = @account.holdings.find_by!(security: security, date: purchase_date)
    assert_equal BigDecimal("114.0"), reverse_purchase_holding.amount
    assert_equal BigDecimal("57.025"), reverse_purchase_holding.cost_basis
  end

  # Synthetic edge case: mini-option contract (is_mini_option: true, 10 shares/contract) — no mini options in k8s
  test "materializes mini-option holdings and calculated cost basis at 10x per-contract value" do
    purchase_date = 2.days.ago.to_date

    process_activities(
      build_option_activity(
        id: "opt_mat_mini_001",
        type: "BUY",
        ticker: "AAPL7 260116C00200000",
        option_type: "CALL",
        strike_price: 200.0,
        expiration_date: "2026-01-16",
        units: 3.0,
        price: 1.25,
        amount: -37.50,
        is_mini_option: true,
        settlement_date: purchase_date.to_s
      )
    )

    security = Security.find_by!(ticker: "AAPL7 260116C00200000")
    Holding::Materializer.new(@account, strategy: :forward).materialize_holdings

    purchase_holding = @account.holdings.find_by!(security: security, date: purchase_date)
    current_holding = @account.holdings.find_by!(security: security, date: Date.current)

    assert_equal BigDecimal("3.0"), purchase_holding.qty
    assert_equal BigDecimal("12.5"), purchase_holding.price
    assert_equal BigDecimal("37.5"), purchase_holding.amount
    assert_equal BigDecimal("12.5"), purchase_holding.cost_basis
    assert_equal "calculated", purchase_holding.cost_basis_source
    assert_equal Money.new(12.5, "USD"), purchase_holding.avg_cost

    assert_equal BigDecimal("37.5"), current_holding.amount
    assert_equal BigDecimal("12.5"), current_holding.cost_basis
  end

  # Modeled on Fidelity TQQQ call and real Robinhood Unity call round-trip option trades (buy 5 @ $10.85/sh, sell 5 @ $14.00/sh)
  test "calculates realized gain/loss for option buy and sell using per-contract prices" do
    purchase_date = 2.days.ago.to_date
    sell_date = Date.current

    process_activities(
      build_option_activity(
        id: "opt_gain_buy_001",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 1.0,
        price: 0.57,
        amount: -57.00,
        settlement_date: purchase_date.to_s
      ),
      build_option_activity(
        id: "opt_gain_sell_001",
        type: "SELL",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: -1.0,
        price: 1.00,
        amount: 100.00,
        settlement_date: sell_date.to_s
      ),
      build_option_activity(
        id: "opt_rh_u_buy",
        type: "BUY",
        symbol: { "symbol" => "U", "description" => "Unity Software Inc." },
        ticker: "U     270115C00015000",
        option_type: "CALL",
        strike_price: 15.0,
        expiration_date: "2027-01-15",
        units: 5.0,
        price: 10.85,
        amount: -5425.0,
        fee: 0.20,
        underlying_symbol: "U",
        settlement_date: purchase_date.to_s
      ),
      build_option_activity(
        id: "opt_rh_u_sell",
        type: "SELL",
        symbol: { "symbol" => "U", "description" => "Unity Software Inc." },
        ticker: "U     270115C00015000",
        option_type: "CALL",
        strike_price: 15.0,
        expiration_date: "2027-01-15",
        units: -5.0,
        price: 14.0,
        amount: 7000.0,
        fee: 0.21,
        underlying_symbol: "U",
        settlement_date: sell_date.to_s
      )
    )

    Holding::Materializer.new(@account, strategy: :forward).materialize_holdings

    sell_trade = snaptrade_entry("opt_gain_sell_001").entryable
    gain_loss = sell_trade.realized_gain_loss

    assert_not_nil gain_loss
    assert_equal Money.new(100.0, "USD"), gain_loss.current
    assert_equal Money.new(57.0, "USD"), gain_loss.previous
    assert_equal Money.new(43.0, "USD"), gain_loss.value

    rh_sell_trade = snaptrade_entry("opt_rh_u_sell").entryable
    rh_gain_loss = rh_sell_trade.realized_gain_loss

    assert_not_nil rh_gain_loss
    assert_equal Money.new(6999.79, "USD"), rh_gain_loss.current
    assert_equal Money.new(5425.20, "USD"), rh_gain_loss.previous
    assert_equal Money.new(1574.59, "USD"), rh_gain_loss.value
  end

  # Synthetic edge case: option contract EXTERNAL_ASSET_TRANSFER (real JNJ transfer was type=TRANSFER, a cash activity)
  test "processes option asset transfers and preserves transfer cost-basis rules" do
    buy_date = 3.days.ago.to_date
    transfer_out_date = 2.days.ago.to_date
    transfer_in_date = Date.yesterday

    process_activities(
      build_option_activity(
        id: "opt_xfer_buy",
        type: "BUY",
        ticker: "JNJ   260116C00125000",
        option_type: "CALL",
        strike_price: 125.0,
        expiration_date: "2026-01-16",
        units: 2.0,
        price: 54.15,
        amount: -10830.00,
        underlying_symbol: "JNJ",
        settlement_date: buy_date.to_s
      ),
      build_option_activity(
        id: "opt_xfer_out",
        type: "EXTERNAL_ASSET_TRANSFER_OUT",
        ticker: "JNJ   260116C00125000",
        option_type: "CALL",
        strike_price: 125.0,
        expiration_date: "2026-01-16",
        units: -1.0,
        price: 54.35,
        amount: nil,
        underlying_symbol: "JNJ",
        settlement_date: transfer_out_date.to_s
      )
    )

    security = Security.find_by!(ticker: "JNJ   260116C00125000")
    Holding::Materializer.new(@account, strategy: :forward).materialize_holdings

    xfer_out_entry = snaptrade_entry("opt_xfer_out")
    assert_equal "Transfer", xfer_out_entry.entryable.investment_activity_label
    assert_equal BigDecimal("-1.0"), xfer_out_entry.entryable.qty
    assert_equal BigDecimal("5435.0"), xfer_out_entry.entryable.price
    assert_equal BigDecimal("0.0"), xfer_out_entry.amount
    assert_nil xfer_out_entry.entryable.realized_gain_loss, "outbound transfer must not realize gain"

    after_out_holding = @account.holdings.find_by!(security: security, date: Date.current)
    assert_equal BigDecimal("1.0"), after_out_holding.qty
    assert_equal BigDecimal("5415.0"), after_out_holding.cost_basis
    assert_equal Money.new(5415.0, "USD"), after_out_holding.avg_cost

    # Now import an inbound option transfer and verify cost basis becomes unknown
    process_activities(
      build_option_activity(
        id: "opt_xfer_in",
        type: "EXTERNAL_ASSET_TRANSFER_IN",
        ticker: "JNJ   260116C00125000",
        option_type: "CALL",
        strike_price: 125.0,
        expiration_date: "2026-01-16",
        units: 1.0,
        price: 54.35,
        amount: nil,
        underlying_symbol: "JNJ",
        settlement_date: transfer_in_date.to_s
      )
    )

    Holding::Materializer.new(@account, strategy: :forward).materialize_holdings

    xfer_in_entry = snaptrade_entry("opt_xfer_in")
    assert_equal "Transfer", xfer_in_entry.entryable.investment_activity_label
    assert_equal BigDecimal("1.0"), xfer_in_entry.entryable.qty
    assert_equal BigDecimal("5435.0"), xfer_in_entry.entryable.price
    assert_equal BigDecimal("0.0"), xfer_in_entry.amount

    after_in_holding = @account.holdings.find_by!(security: security, date: Date.current)
    assert_equal BigDecimal("2.0"), after_in_holding.qty
    assert_nil after_in_holding.cost_basis, "inbound transfer must clear calculated cost basis"
    assert_nil after_in_holding.cost_basis_source
    assert_nil after_in_holding.avg_cost
  end

  # Synthetic edge case: PortfolioCache price-source precedence (db > trade > holding) for option contracts
  test "enforces db > trade > holding price precedence for option contracts in PortfolioCache" do
    process_activities(
      build_option_activity(
        id: "opt_cache_buy_001",
        type: "BUY",
        ticker: "TQQQ  260220C00051000",
        option_type: "CALL",
        strike_price: 51.0,
        expiration_date: "2026-02-20",
        units: 2.0,
        price: 0.57,
        amount: -114.00,
        settlement_date: Date.current.to_s
      )
    )

    security = Security.find_by!(ticker: "TQQQ  260220C00051000")

    @account.holdings.create!(
      security: security,
      date: Date.current,
      currency: "USD",
      qty: 2.0,
      price: 60.0,
      amount: 120.0
    )

    cache_without_db = Holding::PortfolioCache.new(@account, use_holdings: true)
    assert_equal BigDecimal("60.0"), cache_without_db.get_price(security.id, Date.current, source: "holding").price
    assert_equal BigDecimal("57.0"), cache_without_db.get_price(security.id, Date.current, source: "trade").price
    assert_equal BigDecimal("57.0"), cache_without_db.get_price(security.id, Date.current).price,
      "trade price (priority 2, per-contract $57.00) must beat holding price (priority 3)"

    Security::Price.create!(security: security, date: Date.current, price: 62.0, currency: "USD")

    cache_with_db = Holding::PortfolioCache.new(@account, use_holdings: true)
    assert_equal BigDecimal("62.0"), cache_with_db.get_price(security.id, Date.current).price,
      "db price (priority 1) must beat trade price (priority 2) and holding price (priority 3)"
  end

  test "a Wealthsimple card purchase is an outflow named after the merchant" do
    process_activities(card_activity(id: "card_buy", description: "CREDIT_CARD PURCHASE: Corner Grocery #12", amount: -42.50))

    entry = snaptrade_entry("card_buy")
    assert_equal 42.50, entry.amount.to_f
    assert_equal "Corner Grocery #12", entry.name
  end

  test "Wealthsimple card refunds and payments are inflows" do
    process_activities(
      card_activity(id: "card_refund", description: "CREDIT_CARD REFUND: Clothing Store 7", amount: 80.00),
      card_activity(id: "card_payment", description: "CREDIT_CARD PAYMENT", amount: 1200.00)
    )

    assert_equal(-80.00, snaptrade_entry("card_refund").amount.to_f)
    assert_equal "Clothing Store 7", snaptrade_entry("card_refund").name
    assert_equal(-1200.00, snaptrade_entry("card_payment").amount.to_f)
    assert_equal "CREDIT_CARD PAYMENT", snaptrade_entry("card_payment").name
  end

  test "a bare CREDIT_CARD row keeps the provider sign" do
    process_activities(card_activity(id: "card_legacy", description: "CREDIT_CARD", amount: 30.00))

    assert_equal 30.00, snaptrade_entry("card_legacy").amount.to_f
  end

  test "a PREPAID_CARD spend is an outflow" do
    process_activities(card_activity(id: "prepaid", type: "PREPAID_CARD", description: "PREPAID_CARD", amount: -25.00))

    assert_equal 25.00, snaptrade_entry("prepaid").amount.to_f
  end

  test "resyncing renames a SnapTrade card entry and corrects its sign" do
    process_activities(card_activity(id: "card_resync", description: "CREDIT_CARD", amount: -18.40))
    assert_equal(-18.40, snaptrade_entry("card_resync").amount.to_f)

    result = process_activities(card_activity(id: "card_resync", description: "CREDIT_CARD PURCHASE: Food Hall", amount: -18.40))

    assert_equal 0, result[:failed]
    entry = snaptrade_entry("card_resync")
    assert_equal 18.40, entry.amount.to_f
    assert_equal "Food Hall", entry.name
  end

  test "two identical card charges on one day are both kept" do
    process_activities(
      card_activity(id: "park_a", description: "CREDIT_CARD PURCHASE: Parking Lot 4", amount: -6.00),
      card_activity(id: "park_b", description: "CREDIT_CARD PURCHASE: Parking Lot 4", amount: -6.00)
    )

    assert_equal 2, @account.entries.where(source: "snaptrade", external_id: %w[park_a park_b]).count
  end

  test "a pending and a posted copy of one card charge import once, as the posted copy" do
    process_activities(
      card_activity(id: "air_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),
      card_activity(id: "air_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)
    )

    assert_nil snaptrade_entry("air_pending")
    assert_equal 409.69, snaptrade_entry("air_posted").amount.to_f
    assert_equal "Example Airlines", snaptrade_entry("air_posted").name
  end

  test "a pending copy already imported is kept and its posted copy is skipped" do
    process_activities(card_activity(id: "pend_first", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69))

    process_activities(
      card_activity(id: "pend_first", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),
      card_activity(id: "post_later", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)
    )

    assert_not_nil snaptrade_entry("pend_first")
    assert_nil snaptrade_entry("post_later")
  end

  test "merchants that only share a prefix are not merged" do
    process_activities(
      card_activity(id: "corner_12", description: "CREDIT_CARD PURCHASE: Corner Grocery #12", amount: -42.50),
      card_activity(id: "corner_34", description: "CREDIT_CARD PURCHASE: Corner Grocery #34", amount: -42.50)
    )

    assert_equal 2, @account.entries.where(source: "snaptrade", external_id: %w[corner_12 corner_34]).count
  end

  test "a bare CREDIT_CARD row and its merchant-format copy import once" do
    process_activities(
      card_activity(id: "bare_row", description: "CREDIT_CARD", amount: 43.00),
      card_activity(id: "named_row", description: "CREDIT_CARD PURCHASE: Marketplace Ad", amount: -43.00)
    )

    assert_nil snaptrade_entry("bare_row")
    assert_equal "Marketplace Ad", snaptrade_entry("named_row").name
  end

  test "a bare CREDIT_CARD row already imported is kept and nothing is deleted" do
    process_activities(card_activity(id: "old_bare", description: "CREDIT_CARD", amount: 43.00))

    process_activities(
      card_activity(id: "old_bare", description: "CREDIT_CARD", amount: 43.00),
      card_activity(id: "new_named", description: "CREDIT_CARD PURCHASE: Marketplace Ad", amount: -43.00)
    )

    assert_equal 43.00, snaptrade_entry("old_bare").amount.to_f
    assert_nil snaptrade_entry("new_named")
  end

  test "a bare CREDIT_CARD row is not matched with a refund or payment of the same amount" do
    process_activities(
      card_activity(id: "bare_buy", description: "CREDIT_CARD", amount: 43.00),
      card_activity(id: "refund", description: "CREDIT_CARD REFUND: Marketplace Ad", amount: 43.00),
      card_activity(id: "payment", description: "CREDIT_CARD PAYMENT", amount: 43.00)
    )

    assert_not_nil snaptrade_entry("bare_buy")
    assert_not_nil snaptrade_entry("refund")
  end

  test "pending, posted and bare copies of one charge import once" do
    process_activities(
      card_activity(id: "tri_bare", description: "CREDIT_CARD", amount: 409.69),
      card_activity(id: "tri_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),
      card_activity(id: "tri_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)
    )

    assert_equal %w[tri_posted], @account.entries.where(source: "snaptrade", external_id: %w[tri_bare tri_pending tri_posted]).pluck(:external_id)
  end

  test "a pending copy already imported stays the only copy when bare and posted copies arrive" do
    process_activities(card_activity(id: "only_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69))

    process_activities(
      card_activity(id: "only_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),
      card_activity(id: "late_bare", description: "CREDIT_CARD", amount: 409.69),
      card_activity(id: "late_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)
    )

    assert_equal %w[only_pending], @account.entries.where(source: "snaptrade", external_id: %w[only_pending late_bare late_posted]).pluck(:external_id)
  end

  test "only an exact bare CREDIT_CARD description is matched with a purchase" do
    process_activities(
      card_activity(id: "card_fee", description: "CREDIT_CARD FEE", amount: 43.00),
      card_activity(id: "fee_day_buy", description: "CREDIT_CARD PURCHASE: Marketplace Ad", amount: -43.00)
    )

    assert_not_nil snaptrade_entry("card_fee")
    assert_not_nil snaptrade_entry("fee_day_buy")
  end

  test "card charges with different amounts or merchants are not merged" do
    process_activities(
      card_activity(id: "diff_a", description: "CREDIT_CARD PURCHASE: Grocer", amount: -10.00),
      card_activity(id: "diff_b", description: "CREDIT_CARD PURCHASE: Grocer", amount: -11.00),
      card_activity(id: "diff_c", description: "CREDIT_CARD PURCHASE: Pharmacy", amount: -10.00)
    )

    assert_equal 3, @account.entries.where(source: "snaptrade", external_id: %w[diff_a diff_b diff_c]).count
  end

  test "a non-hash element in the payload does not stop card processing" do
    result = process_activities(
      nil,
      card_activity(id: "after_nil_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -20.00),
      card_activity(id: "after_nil_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -20.00)
    )

    assert_not_nil result
    assert_not_nil snaptrade_entry("after_nil_posted")
    assert_nil snaptrade_entry("after_nil_pending")
  end

  test "card rows are compared by their effective cash amount" do
    pending = card_activity(id: "net_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: nil)
    posted = card_activity(id: "net_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: nil)
    pending["net_amount"] = -10.00
    posted["net_amount"] = -11.00

    process_activities(pending, posted)

    assert_equal 2, @account.entries.where(source: "snaptrade", external_id: %w[net_pending net_posted]).count
  end

  private

    def card_activity(id:, description:, amount:, type: "CREDIT_CARD")
      {
        "id" => id,
        "type" => type,
        "amount" => amount,
        "description" => description,
        "trade_date" => Date.current.to_s,
        "settlement_date" => Date.current.to_s,
        "currency" => { "code" => "USD" }
      }
    end

    def process_activities(*activities)
      @snaptrade_account.update!(raw_activities_payload: activities)
      SnaptradeAccount::ActivitiesProcessor.new(@snaptrade_account).process
    end

    def snaptrade_entry(external_id)
      @account.entries.find_by(external_id: external_id, source: "snaptrade")
    end

    def snaptrade_debug_log(activity_id, category: "provider_sync", level: "warn")
      DebugLogEntry.where(provider_key: "snaptrade", category: category, level: level)
                   .find { |log| log.metadata["activity_id"] == activity_id }
    end

    def build_trade_activity(id:, type:, symbol:, units:, price:, settlement_date: Date.current.to_s, amount: nil, fee: nil)
      activity = {
        "id" => id,
        "type" => type,
        "symbol" => {
          "symbol" => symbol,
          "description" => "#{symbol} Inc"
        },
        "units" => units,
        "price" => price,
        "settlement_date" => settlement_date,
        "currency" => { "code" => "USD" }
      }
      activity["amount"] = amount unless amount.nil?
      activity["fee"] = fee unless fee.nil?
      activity
    end

    def build_cash_activity(id:, type:, amount:, settlement_date:, symbol: nil)
      activity = {
        "id" => id,
        "type" => type,
        "amount" => amount,
        "settlement_date" => settlement_date,
        "currency" => { "code" => "USD" }
      }

      if symbol
        activity["symbol"] = {
          "symbol" => symbol,
          "description" => "#{symbol} Fund"
        }
      end

      activity
    end

    def build_option_activity(id:, type:, ticker:, strike_price:, option_type:, expiration_date:, units:, price:, amount: nil, fee: nil, underlying_symbol: nil, symbol: nil, description: nil, is_mini_option: false, settlement_date: Date.current.to_s)
      underlying = underlying_symbol || ticker.split.first
      activity = {
        "id" => id,
        "type" => type,
        "symbol" => symbol,
        "units" => units,
        "price" => price,
        "settlement_date" => settlement_date,
        "currency" => { "code" => "USD" },
        "option_symbol" => {
          "id" => SecureRandom.uuid,
          "ticker" => ticker,
          "option_type" => option_type,
          "strike_price" => strike_price,
          "expiration_date" => expiration_date,
          "is_mini_option" => is_mini_option,
          "underlying_symbol" => {
            "id" => SecureRandom.uuid,
            "symbol" => underlying,
            "raw_symbol" => underlying,
            "description" => "#{underlying} Underlying Inc.",
            "currency" => { "code" => "USD" },
            "exchange" => { "code" => "NASDAQ", "mic_code" => "XNAS" }
          }
        }
      }
      activity["amount"] = amount unless amount.nil?
      activity["fee"] = fee unless fee.nil?
      activity["description"] = description if description.present?
      activity
    end
end