-- Migration 002: Add version column for Optimistic Locking
-- Purpose: Enable concurrent transaction safety for deposit balance updates
-- Date: 2026-01-19
-- Reference: CLAUDE.md "Transaction Isolation & Optimistic Locking"

-- Problem:
--   D1 batch() is not a true transaction - partial failures can cause data inconsistencies
--   in financial operations (balance updates + transaction records)

-- Solution:
--   Optimistic Locking pattern with version column
--   - Version is incremented on every balance UPDATE
--   - UPDATE checks current version to detect concurrent modifications
--   - Automatic retry with exponential backoff (max 3 attempts)

-- Add version column to user_deposits
ALTER TABLE user_deposits ADD COLUMN version INTEGER NOT NULL DEFAULT 1;

-- Create index for efficient version checking
CREATE INDEX IF NOT EXISTS idx_deposits_user_version ON user_deposits(user_id, version);

-- Verification:
--   SELECT user_id, balance, version FROM user_deposits LIMIT 5;

-- Rollback instructions (manual execution required):
--   DROP INDEX IF EXISTS idx_deposits_user_version;
--   -- Note: SQLite doesn't support DROP COLUMN directly in older versions
--   -- If needed, recreate table without version column and copy data
