-- Delegated Users Feature
-- Allows main users to create sub-accounts with limited permissions to their resources

USE whp;

-- Create delegated users table
CREATE TABLE IF NOT EXISTS delegated_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(32) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    parent_username VARCHAR(32) NOT NULL,
    display_name VARCHAR(100) DEFAULT NULL,
    email VARCHAR(255) DEFAULT NULL,
    
    -- Permission flags for what this delegated user can access
    can_manage_domains BOOLEAN DEFAULT FALSE,
    can_manage_sites BOOLEAN DEFAULT FALSE, 
    can_manage_databases BOOLEAN DEFAULT FALSE,
    can_manage_email BOOLEAN DEFAULT FALSE,
    can_manage_files BOOLEAN DEFAULT FALSE,
    can_manage_backups BOOLEAN DEFAULT FALSE,
    can_view_terminal BOOLEAN DEFAULT FALSE,
    can_manage_wordpress BOOLEAN DEFAULT FALSE,
    
    -- Resource restrictions
    allowed_domains TEXT DEFAULT NULL, -- JSON array of specific domains they can access (null = all parent domains)
    max_domains INT DEFAULT NULL, -- Maximum domains they can create (null = unlimited within parent's allowance)
    max_databases INT DEFAULT NULL, -- Maximum databases they can create
    max_email_accounts INT DEFAULT NULL, -- Maximum email accounts they can create
    
    -- Status and tracking
    is_active BOOLEAN DEFAULT TRUE,
    last_login TIMESTAMP NULL DEFAULT NULL,
    failed_login_attempts INT DEFAULT 0,
    locked_until TIMESTAMP NULL DEFAULT NULL,
    
    -- Metadata
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    created_by VARCHAR(32) NOT NULL, -- Who created this delegated user
    
    -- Indexes and constraints
    INDEX idx_parent_username (parent_username),
    INDEX idx_username (username),
    INDEX idx_is_active (is_active),
    INDEX idx_created_by (created_by),
    
    -- Ensure delegated username doesn't conflict with system users
    CONSTRAINT chk_delegated_username_format CHECK (username REGEXP '^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$'),
    CONSTRAINT chk_username_length CHECK (CHAR_LENGTH(username) >= 3 AND CHAR_LENGTH(username) <= 32)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create delegated user sessions table for session management
CREATE TABLE IF NOT EXISTS delegated_user_sessions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(128) NOT NULL UNIQUE,
    delegated_user_id INT NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    user_agent TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NOT NULL,
    
    INDEX idx_session_id (session_id),
    INDEX idx_delegated_user_id (delegated_user_id),
    INDEX idx_expires_at (expires_at),
    
    FOREIGN KEY (delegated_user_id) REFERENCES delegated_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create delegated user activity log for audit trail
CREATE TABLE IF NOT EXISTS delegated_user_activity (
    id INT AUTO_INCREMENT PRIMARY KEY,
    delegated_user_id INT NOT NULL,
    action VARCHAR(100) NOT NULL,
    resource_type VARCHAR(50) DEFAULT NULL, -- domain, database, email, etc.
    resource_id VARCHAR(100) DEFAULT NULL, -- specific resource identifier
    details TEXT DEFAULT NULL, -- JSON details about the action
    ip_address VARCHAR(45) NOT NULL,
    user_agent TEXT,
    result ENUM('success', 'failure', 'unauthorized') NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    INDEX idx_delegated_user_id (delegated_user_id),
    INDEX idx_action (action),
    INDEX idx_resource_type (resource_type),
    INDEX idx_created_at (created_at),
    INDEX idx_result (result),
    
    FOREIGN KEY (delegated_user_id) REFERENCES delegated_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Add trigger to automatically clean up expired sessions
DELIMITER //
CREATE TRIGGER IF NOT EXISTS cleanup_expired_delegated_sessions
    BEFORE INSERT ON delegated_user_sessions
    FOR EACH ROW
BEGIN
    DELETE FROM delegated_user_sessions 
    WHERE expires_at < NOW();
END//
DELIMITER ;

-- Create view for active delegated users with parent info
CREATE VIEW IF NOT EXISTS active_delegated_users AS
SELECT 
    du.id,
    du.username,
    du.parent_username,
    du.display_name,
    du.email,
    du.can_manage_domains,
    du.can_manage_sites,
    du.can_manage_databases,
    du.can_manage_email,
    du.can_manage_files,
    du.can_manage_backups,
    du.can_view_terminal,
    du.can_manage_wordpress,
    du.allowed_domains,
    du.max_domains,
    du.max_databases,
    du.max_email_accounts,
    du.last_login,
    du.created_at,
    du.created_by,
    ca.max_domains as parent_max_domains,
    ca.max_email_accounts as parent_max_email_accounts
FROM delegated_users du
LEFT JOIN client_allowances ca ON ca.username = du.parent_username
WHERE du.is_active = TRUE;