-- Session State Table for Data Persistence
-- This table stores critical timing and context variables for crash recovery

CREATE TABLE IF NOT EXISTS session_state (
    id INT AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(255) UNIQUE NOT NULL,
    production_start_time BIGINT,
    operating_time DOUBLE DEFAULT 0,
    last_update_time BIGINT,
    tracking_enabled TINYINT(1) DEFAULT 0,
    cycle_count INT DEFAULT 0,
    active_work_order_id VARCHAR(255),
    active_work_order_data JSON,
    machine_online TINYINT(1) DEFAULT 1,
    production_started TINYINT(1) DEFAULT 0,
    last_cycle_time BIGINT,
    last_machine_state INT DEFAULT 0,
    created_at BIGINT NOT NULL,
    updated_at BIGINT NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    INDEX idx_session_id (session_id),
    INDEX idx_is_active (is_active),
    INDEX idx_updated_at (updated_at)
);

-- Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_active_work_order ON session_state(active_work_order_id);
CREATE INDEX IF NOT EXISTS idx_session_active ON session_state(session_id, is_active);
