-- =====================================================
-- SCRIPT 01: Create Application Versions Infrastructure
-- =====================================================
-- Date: 2025-11-25
-- Purpose: Create appversions table for tracking application versions
-- Status: REVERSIBLE (see ROLLBACK_01)
-- Estimated Time: < 1 minute
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- =====================================================
-- STEP 1: Create appversions table
-- =====================================================

CREATE TABLE IF NOT EXISTS appversions (
    appversionid INT(11) PRIMARY KEY AUTO_INCREMENT,
    appid TINYINT(4) NOT NULL,
    version VARCHAR(50) NOT NULL,
    releasedate DATE NULL,
    notes VARCHAR(255) NULL,
    isactive BIT(1) DEFAULT b'1',
    dateadded DATETIME DEFAULT CURRENT_TIMESTAMP,

    -- Indexes
    KEY idx_appid (appid),
    KEY idx_version (version),
    KEY idx_isactive (isactive),

    -- Unique constraint: one version string per application
    UNIQUE KEY uk_app_version (appid, version),

    -- Foreign Key
    CONSTRAINT fk_appversions_appid FOREIGN KEY (appid) REFERENCES applications(appid)
        ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
COMMENT='Application version tracking for installed software';

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

SELECT '✓ appversions table created' AS status;
SELECT
    TABLE_NAME,
    ENGINE,
    TABLE_ROWS,
    TABLE_COMMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'shopdb' AND TABLE_NAME = 'appversions';

SELECT '✓ Script 01 completed successfully' AS status;

SET SQL_SAFE_UPDATES = 1;

-- =====================================================
-- NOTES
-- =====================================================
-- Next: Run script 02_add_appversionid_to_installedapps.sql
-- Rollback: Run ROLLBACK_01_appversions_table.sql
-- =====================================================
