-- ==============================================================================
-- 🗄️ Conversation States Table Schema
-- Persists multi-stage flow sessions for WhatsApp contacts.
-- ==============================================================================

CREATE TABLE IF NOT EXISTS `conversation_states` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `company_id` INT NOT NULL,
    `contact_phone` VARCHAR(512) NOT NULL COMMENT 'Encrypted using AES-256-GCM',
    `contact_phone_hash` VARCHAR(64) NOT NULL COMMENT 'HMAC-SHA256 Blind Index',
    `flow_name` VARCHAR(100) NOT NULL COMMENT 'e.g. test_flow, registration',
    `current_step` VARCHAR(100) NOT NULL,
    `context_data` JSON DEFAULT NULL COMMENT 'Stores transient state data',
    `expires_at` TIMESTAMP NOT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `unique_company_contact` (`company_id`, `contact_phone_hash`),
    FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE,
    INDEX `idx_conv_expires` (`expires_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
