-- Phase 1 — entity-merge review queue.
--
-- ADDITIVE/REVERSIBLE. The fuzzy (local-Qwen) tier no longer auto-merges; it
-- writes CANDIDATES here for a human to approve (same entity -> merge) or reject
-- (different entities -> keep separate), surfaced in the CRM web UI. Approved
-- candidates apply the merge and are recorded in entity_merges (durable);
-- rejected pairs are remembered so they are not re-surfaced.

CREATE TABLE IF NOT EXISTS entity_merge_candidates (
    id          TEXT PRIMARY KEY,
    entity_a    TEXT NOT NULL,      -- survivor (kept) canonical id
    entity_b    TEXT NOT NULL,      -- would be merged INTO entity_a
    name_a      TEXT, name_b TEXT,
    email_a     TEXT, email_b TEXT,
    context     TEXT,               -- firm / surname context for the reviewer
    verdict     TEXT,               -- 'same' | 'different' (local-Qwen suggestion)
    confidence  REAL,
    reason      TEXT,               -- Qwen's reasoning (why it thinks same/different)
    status      TEXT NOT NULL DEFAULT 'pending',   -- pending | approved | rejected
    decided_by  TEXT,               -- users.id of the partner who decided
    decided_at  TEXT,
    created_at  TEXT DEFAULT (datetime('now')),
    UNIQUE(entity_a, entity_b)
);
CREATE INDEX IF NOT EXISTS idx_merge_candidates_status ON entity_merge_candidates(status);
