-- ============================================================================
-- CryptoWallet API — Database Schema
-- Idempotent: safe to run multiple times (CREATE IF NOT EXISTS).
--
-- Применение:
--   psql "postgresql://user:pass@host:5432/db" -f deployserver/db/schema.sql
-- ============================================================================

-- ── users ───────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users (
  id                VARCHAR(26) PRIMARY KEY,
  email             VARCHAR(255) NOT NULL UNIQUE,
  password_hash     VARCHAR(255) NOT NULL,
  last_name         VARCHAR(128),
  first_name        VARCHAR(128),
  middle_name       VARCHAR(128),
  birth_date        DATE,
  crypto_wallet     VARCHAR(255),
  phone             VARCHAR(16),
  bik               VARCHAR(9),
  account_number    VARCHAR(20),
  card_number       VARCHAR(19),
  inn               VARCHAR(12),
  kyc_verified      BOOLEAN NOT NULL DEFAULT FALSE,
  kyc_verified_at   TIMESTAMPTZ,
  is_deleted        BOOLEAN NOT NULL DEFAULT FALSE,
  created_at        TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at        TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- ── wallets ─────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS wallets (
  id                VARCHAR(26) PRIMARY KEY,
  user_id           VARCHAR(26) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  chain             VARCHAR(10) NOT NULL,
  address           VARCHAR(256) NOT NULL,
  derivation_path   VARCHAR(64) NOT NULL,
  created_at        TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT wallets_user_id_chain_unique UNIQUE (user_id, chain)
);

CREATE INDEX IF NOT EXISTS idx_wallets_user_id ON wallets(user_id);
CREATE INDEX IF NOT EXISTS idx_wallets_address ON wallets(address);

-- ── sessions ────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS sessions (
  id                  VARCHAR(26) PRIMARY KEY,
  sid                 VARCHAR(26) NOT NULL UNIQUE,
  user_id             VARCHAR(26) NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  device_id           VARCHAR(26),
  user_agent          VARCHAR(500),
  first_ip            VARCHAR(64),
  last_ip             VARCHAR(64),
  last_seen_at        TIMESTAMPTZ,
  revoked_at          TIMESTAMPTZ,
  refresh_jti_hash    VARCHAR(255),
  refresh_expires_at  TIMESTAMPTZ,
  created_at          TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at          TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_sid ON sessions(sid);
