-- =====================================================
-- ROLLBACK 02: Remove Machines Table Extensions
-- =====================================================
-- Date: 2025-11-06
-- Purpose: Rollback script 02_extend_machines_table.sql
-- WARNING: This will DELETE all data in new columns
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- =====================================================
-- STEP 1: Drop foreign keys first (if they exist)
-- =====================================================

SET @stmt = (SELECT IF(
    (SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS
     WHERE CONSTRAINT_SCHEMA = 'shopdb'
       AND TABLE_NAME = 'machines'
       AND CONSTRAINT_NAME = 'fk_machines_machinestatusid') > 0,
    'ALTER TABLE machines DROP FOREIGN KEY fk_machines_machinestatusid',
    'SELECT "FK fk_machines_machinestatusid does not exist"'
));
PREPARE stmt FROM @stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- =====================================================
-- STEP 2: Drop indexes
-- =====================================================

DROP INDEX IF EXISTS idx_machines_hostname ON machines;
DROP INDEX IF EXISTS idx_machines_serialnumber ON machines;
DROP INDEX IF EXISTS idx_machines_pctypeid ON machines;
DROP INDEX IF EXISTS idx_machines_osid ON machines;
DROP INDEX IF EXISTS idx_machines_machinestatusid ON machines;
DROP INDEX IF EXISTS idx_machines_lastupdated ON machines;
DROP INDEX IF EXISTS idx_machines_controllertypeid ON machines;
DROP INDEX IF EXISTS idx_machines_controllerosid ON machines;

-- =====================================================
-- STEP 3: Remove columns
-- =====================================================

ALTER TABLE machines
DROP COLUMN IF EXISTS hostname,
DROP COLUMN IF EXISTS loggedinuser,
DROP COLUMN IF EXISTS serialnumber,
DROP COLUMN IF EXISTS osid,
DROP COLUMN IF EXISTS machinestatusid,
DROP COLUMN IF EXISTS pctypeid,
DROP COLUMN IF EXISTS controllertypeid,
DROP COLUMN IF EXISTS controllerosid,
DROP COLUMN IF EXISTS requires_manual_machine_config,
DROP COLUMN IF EXISTS lastupdated,
DROP COLUMN IF EXISTS dateadded;

-- =====================================================
-- VERIFICATION
-- =====================================================

SELECT '✓ Foreign keys dropped' AS status;
SELECT '✓ Indexes dropped' AS status;
SELECT '✓ Columns removed from machines table' AS status;
DESCRIBE machines;
SELECT '✓ ROLLBACK 02 completed successfully' AS status;

SET SQL_SAFE_UPDATES = 1;

-- =====================================================
-- NOTES
-- =====================================================
-- Columns removed:
-- - hostname, loggedinuser, serialnumber
-- - osid, machinestatusid, pctypeid
-- - controllertypeid, controllerosid
-- - requires_manual_machine_config
-- - lastupdated, dateadded
--
-- To restore: Run 02_extend_machines_table.sql
-- =====================================================
