-- =====================================================
-- ROLLBACK 03: Remove appid from notifications
-- =====================================================
-- Date: 2025-11-25
-- Purpose: Rollback script for 03_add_appid_to_notifications.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 = 'notifications'
    AND CONSTRAINT_NAME = 'fk_notifications_appid'
);

SET @sql = IF(@fk_exists > 0,
    'ALTER TABLE notifications DROP FOREIGN KEY fk_notifications_appid',
    '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 = 'notifications'
    AND INDEX_NAME = 'idx_notifications_appid'
);

SET @sql = IF(@idx_exists > 0,
    'ALTER TABLE notifications DROP INDEX idx_notifications_appid',
    '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 = 'notifications'
    AND COLUMN_NAME = 'appid'
);

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

SELECT '✓ appid removed from notifications' AS status;

SET SQL_SAFE_UPDATES = 1;
