-- 027_cian_session_cookies.sql
-- Purpose: Encrypted storage for Cian browser session cookies needed to call
--          the Valuation Calculator endpoint (auth required).
--          Uses pgcrypto pgp_sym_encrypt for AES encryption at rest.
-- Dependencies:
--   - pgcrypto extension (installed here via CREATE EXTENSION IF NOT EXISTS)
-- Deploy order: Apply after 026.
--
-- Security notes:
--   - cookies_encrypted stores AES-encrypted JSON blob via pgp_sym_encrypt.
--   - Encryption key lives in .env.runtime (COOKIE_ENCRYPTION_KEY), never in DB.
--   - Access restricted to admin-token-gated API endpoint only.
--
-- Sources: CianScraper_v1_Implementation_Plan (Cookie auth section)

BEGIN;

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS cian_session_cookies (
    account_user_id     bigint      PRIMARY KEY,      -- Cian user_id extracted from state.user.userId
    cookies_encrypted   bytea       NOT NULL,          -- pgp_sym_encrypt(json_cookies, key)
    expires_at_estimate timestamptz NOT NULL,          -- estimated expiry (~30 days from upload)
    uploaded_at         timestamptz NOT NULL DEFAULT NOW(),
    last_used_at        timestamptz,                   -- set on each successful valuation call
    last_invalid_at     timestamptz,                   -- set when isAuthenticated=false detected
    notes               text                           -- e.g. 'Account: lekss361@cian.ru'
);

-- Most recent upload first (admin dashboard ordering)
CREATE INDEX IF NOT EXISTS cian_cookies_uploaded_idx
  ON cian_session_cookies (uploaded_at DESC);

-- Active session lookup (non-expired and not invalidated)
CREATE INDEX IF NOT EXISTS cian_cookies_active_idx
  ON cian_session_cookies (expires_at_estimate)
  WHERE last_invalid_at IS NULL;

COMMIT;
