-- 182_trade_in_leads_consent_proof.sql
-- LOW audit R2 (#9): durable 152-ФЗ proof-of-consent for trade_in_leads.
--
-- WHY:
--   #2497 already computes client_ip (X-Forwarded-For, fallback direct peer)
--   and pins _CONSENT_POLICY_VERSION = "2026-07" in app/api/v1/lead.py, but
--   both were written ONLY to the audit log — trade_in_leads had no columns
--   to hold them (explicit TODO at the INSERT in lead.py). A bare boolean
--   `consent` column plus a log line is not durable proof: logs rotate/expire,
--   the row itself carries no evidence of what was agreed to, under what
--   policy version, or from what IP.
--
-- WHAT:
--   Three nullable columns on trade_in_leads:
--     - client_ip (inet)              — same value already computed in
--                                        create_trade_in_lead, now persisted
--                                        per-row instead of log-only.
--     - consent_policy_version (text) — snapshot of _CONSENT_POLICY_VERSION
--                                        at the time this lead was captured.
--     - consent_text_snapshot (text)  — snapshot of the exact consent sentence
--                                        shown to the user (_CONSENT_TEXT_SNAPSHOT
--                                        in lead.py, same PR).
--
-- IDEMPOTENCY / SAFETY:
--   ADD COLUMN IF NOT EXISTS x3 — safe re-run. All nullable, no DEFAULT, no
--   backfill: existing rows keep NULL (no consent proof was captured for them
--   pre-migration — that's an honest reflection of what actually happened,
--   not a schema gap). Purely additive: no existing reads/writes break.
--
-- Dependencies: 172_trade_in_leads.sql (trade_in_leads table).

BEGIN;

ALTER TABLE trade_in_leads
    ADD COLUMN IF NOT EXISTS client_ip inet,
    ADD COLUMN IF NOT EXISTS consent_policy_version text,
    ADD COLUMN IF NOT EXISTS consent_text_snapshot text;

COMMENT ON COLUMN trade_in_leads.client_ip IS '152-ФЗ proof-of-consent: клиентский IP на момент согласия (ранее только в audit-логе, #2497 TODO).';
COMMENT ON COLUMN trade_in_leads.consent_policy_version IS '152-ФЗ proof-of-consent: снимок _CONSENT_POLICY_VERSION на момент согласия.';
COMMENT ON COLUMN trade_in_leads.consent_text_snapshot IS '152-ФЗ proof-of-consent: снимок текста согласия, показанного пользователю (_CONSENT_TEXT_SNAPSHOT).';

COMMIT;
