-- ============================================================================
-- AUTO-LAUNCH MODULES MIGRATION
-- ============================================================================
-- Description: Creates table for auto-launching modules based on user groups
-- Author: AI Assistant
-- Date: November 10, 2025
-- Dependencies: modules table must exist
-- ============================================================================

-- Create auto_launch_modules table
CREATE TABLE IF NOT EXISTS auto_launch_modules (
    id SERIAL PRIMARY KEY,
    group_name VARCHAR(100) NOT NULL,
    module_name VARCHAR(100) NOT NULL,
    module_id UUID,
    priority INTEGER DEFAULT 1,
    enabled BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign key constraint (optional, allows modules to be deleted)
    CONSTRAINT fk_auto_launch_module_id 
        FOREIGN KEY (module_id) 
        REFERENCES modules(module_id) 
        ON DELETE SET NULL,
    
    -- Ensure unique combination of group and module
    CONSTRAINT unique_group_module 
        UNIQUE(group_name, module_name)
);

-- Create index for faster lookups by group_name
CREATE INDEX IF NOT EXISTS idx_auto_launch_group_name 
ON auto_launch_modules(group_name);

-- Create index for enabled modules
CREATE INDEX IF NOT EXISTS idx_auto_launch_enabled 
ON auto_launch_modules(enabled) WHERE enabled = true;

-- Insert sample auto-launch configurations
INSERT INTO auto_launch_modules (group_name, module_name, module_id, priority, enabled) VALUES
-- Cashiers automatically open POS
('cashiers', 'POS', '0194a8b2-0015-7123-8123-123456789abc'::uuid, 1, true),

-- Managers open System Settings
('managers', 'SystemSettings', '0194a8b2-0001-7123-8123-123456789abc'::uuid, 1, true),

-- Inventory staff open Inventory Management
('inventory_staff', 'InventoryManagement', '0194a8b2-0016-7123-8123-123456789abc'::uuid, 1, true),

-- Supervisors open Customer Management
('supervisors', 'Customer Management', '0194a8b2-0fff-7123-8123-123456789afe'::uuid, 1, true),

-- HR staff open Open Positions
('hr_staff', 'Open Positions', '6861955c-f882-44db-ab95-89c1a9b8e307'::uuid, 1, true);

-- Add comments for documentation
COMMENT ON TABLE auto_launch_modules IS 'Configuration for automatically launching modules based on user group membership';
COMMENT ON COLUMN auto_launch_modules.group_name IS 'Name of the user group (e.g., cashiers, managers, supervisors)';
COMMENT ON COLUMN auto_launch_modules.module_name IS 'Name of the module to auto-launch';
COMMENT ON COLUMN auto_launch_modules.module_id IS 'UUID reference to the modules table';
COMMENT ON COLUMN auto_launch_modules.priority IS 'Launch order priority (lower numbers launch first)';
COMMENT ON COLUMN auto_launch_modules.enabled IS 'Whether auto-launch is active for this group/module combination';