-- Add terminate_requested to devices tables so dashboard can request app exit.
-- Idempotent: add column only if table exists and column is missing.
-- Skips cleanly if devices/ftt_devices do not exist (e.g. 003 not applied).

SET @db = DATABASE();

-- devices: alter only if table exists and column missing
SET @tbl = 'devices';
SET @tbl_exists = (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = @db AND TABLE_NAME = @tbl);
SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = @tbl AND COLUMN_NAME = 'terminate_requested');
SET @sql = IF(@tbl_exists > 0 AND @col_exists = 0, 'ALTER TABLE devices ADD COLUMN terminate_requested TINYINT(1) NOT NULL DEFAULT 0 AFTER reports_enabled', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- ftt_devices: alter only if table exists and column missing
SET @tbl = 'ftt_devices';
SET @tbl_exists = (SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = @db AND TABLE_NAME = @tbl);
SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = @tbl AND COLUMN_NAME = 'terminate_requested');
SET @sql = IF(@tbl_exists > 0 AND @col_exists = 0, 'ALTER TABLE ftt_devices ADD COLUMN terminate_requested TINYINT(1) NOT NULL DEFAULT 0 AFTER reports_enabled', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
