-- =====================================================
-- ROLLBACK 02: Remove appversionid from installedapps
-- =====================================================
-- Date: 2025-11-25
-- Purpose: Rollback script for 02_add_appversionid_to_installedapps.sql
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- Drop FK first
SET @fk_exists = (
    SELECT COUNT(*)
    FROM information_schema.TABLE_CONSTRAINTS
    WHERE TABLE_SCHEMA = 'shopdb'
    AND TABLE_NAME = 'installedapps'
    AND CONSTRAINT_NAME = 'fk_installedapps_appversionid'
);

SET @sql = IF(@fk_exists > 0,
    'ALTER TABLE installedapps DROP FOREIGN KEY fk_installedapps_appversionid',
    'SELECT "FK does not exist" AS status'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Drop index
SET @idx_exists = (
    SELECT COUNT(*)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = 'shopdb'
    AND TABLE_NAME = 'installedapps'
    AND INDEX_NAME = 'idx_appversionid'
);

SET @sql = IF(@idx_exists > 0,
    'ALTER TABLE installedapps DROP INDEX idx_appversionid',
    'SELECT "Index does not exist" AS status'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Drop column
SET @column_exists = (
    SELECT COUNT(*)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = 'shopdb'
    AND TABLE_NAME = 'installedapps'
    AND COLUMN_NAME = 'appversionid'
);

SET @sql = IF(@column_exists > 0,
    'ALTER TABLE installedapps DROP COLUMN appversionid',
    'SELECT "Column does not exist" AS status'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT '✓ appversionid removed from installedapps' AS status;

SET SQL_SAFE_UPDATES = 1;
