-- Migration: Add idempotency_key column to server_orders table
-- Purpose: Prevent duplicate order creation on Queue retry
-- Date: 2026-01-28

-- Note: This migration should be run on telegram-conversations database (USER_DB)
-- SQLite doesn't allow adding UNIQUE column directly, so we add column + UNIQUE INDEX

-- Step 1: Add idempotency_key column (without UNIQUE constraint)
ALTER TABLE server_orders ADD COLUMN idempotency_key TEXT;

-- Step 2: Create UNIQUE index (this enforces uniqueness for non-NULL values)
CREATE UNIQUE INDEX IF NOT EXISTS idx_server_orders_idempotency_unique
  ON server_orders(idempotency_key)
  WHERE idempotency_key IS NOT NULL;

-- Verification query (run after migration):
-- SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name='server_orders' AND name LIKE '%idempotency%';
