-- 2026-05-21: interest_field_history table.
--
-- Captures field-level overrides - every time a value on an interest
-- or its linked client changes via a supplemental-info form (or any
-- future channel that explicitly records overrides), a row lands here
-- with the old + new values plus source attribution.
--
-- Why a separate table vs piggybacking on `audit_logs`:
--   - audit_logs is a fire-hose of every CRUD event (~10k rows/day on
--     a busy port). Filtering for a single field's history is slow.
--   - This table holds ONLY explicit overrides - much smaller, easier
--     to surface on the Interest / Client detail "Field history" panel.
--   - The `source` column lets the UI render meaningful provenance
--     ("Submitted via supplemental info form on 2026-05-21").

CREATE TABLE IF NOT EXISTS interest_field_history (
  id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
  port_id text NOT NULL REFERENCES ports(id),
  interest_id text REFERENCES interests(id) ON DELETE CASCADE,
  client_id text REFERENCES clients(id) ON DELETE CASCADE,
  field_path text NOT NULL,
  old_value jsonb,
  new_value jsonb NOT NULL,
  source text NOT NULL,
  submission_id text,
  created_at timestamptz NOT NULL DEFAULT now(),
  created_by text
);

CREATE INDEX IF NOT EXISTS idx_ifh_interest_created
  ON interest_field_history (port_id, interest_id, created_at DESC)
  WHERE interest_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_ifh_client_created
  ON interest_field_history (port_id, client_id, created_at DESC)
  WHERE client_id IS NOT NULL;
