-- Backup System Database Schema
-- Date: 2025-01-17
-- Description: Adds tables for backup system including S3 targets, backup history, and scheduling

USE whp;

-- Create backup targets table
CREATE TABLE IF NOT EXISTS backup_targets (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    type ENUM('s3', 'local') NOT NULL DEFAULT 's3',
    endpoint VARCHAR(255) NOT NULL,
    bucket VARCHAR(100) NOT NULL,
    access_key VARCHAR(100) NOT NULL,
    secret_key VARCHAR(255) NOT NULL,
    region VARCHAR(50) DEFAULT 'us-east-1',
    path_prefix VARCHAR(255) DEFAULT '',
    retention_days INT DEFAULT 30,
    max_backups INT DEFAULT 10,
    is_global BOOLEAN DEFAULT FALSE,
    owner VARCHAR(50) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_owner (owner),
    INDEX idx_global (is_global)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Create backup history table
CREATE TABLE IF NOT EXISTS backup_history (
    id INT AUTO_INCREMENT PRIMARY KEY,
    target_id INT NOT NULL,
    user VARCHAR(50) NOT NULL,
    backup_type ENUM('site', 'userfiles', 'database') NOT NULL,
    backup_name VARCHAR(255) NOT NULL,
    backup_path VARCHAR(500) NOT NULL,
    backup_size BIGINT DEFAULT 0,
    status ENUM('pending', 'running', 'completed', 'failed', 'deleted') NOT NULL DEFAULT 'pending',
    error_message TEXT DEFAULT NULL,
    started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP NULL DEFAULT NULL,
    metadata JSON DEFAULT NULL,
    FOREIGN KEY (target_id) REFERENCES backup_targets(id) ON DELETE CASCADE,
    INDEX idx_user (user),
    INDEX idx_status (status),
    INDEX idx_started_at (started_at),
    INDEX idx_target_user (target_id, user)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Create backup schedules table
CREATE TABLE IF NOT EXISTS backup_schedules (
    id INT AUTO_INCREMENT PRIMARY KEY,
    target_id INT NOT NULL,
    user VARCHAR(50) NOT NULL,
    backup_type ENUM('site', 'userfiles', 'database', 'all') NOT NULL,
    backup_name VARCHAR(255) NOT NULL,
    schedule_type ENUM('hourly', 'daily', 'weekly', 'monthly') NOT NULL,
    schedule_time TIME DEFAULT '00:00:00',
    schedule_day INT DEFAULT NULL,
    enabled BOOLEAN DEFAULT TRUE,
    last_run TIMESTAMP NULL DEFAULT NULL,
    next_run TIMESTAMP NULL DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (target_id) REFERENCES backup_targets(id) ON DELETE CASCADE,
    INDEX idx_user (user),
    INDEX idx_enabled (enabled),
    INDEX idx_next_run (next_run)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Create backup queue table for async processing
CREATE TABLE IF NOT EXISTS backup_queue (
    id INT AUTO_INCREMENT PRIMARY KEY,
    target_id INT NOT NULL,
    user VARCHAR(50) NOT NULL,
    backup_type ENUM('site', 'userfiles', 'database') NOT NULL,
    backup_name VARCHAR(255) NOT NULL,
    priority ENUM('low', 'normal', 'high') DEFAULT 'normal',
    status ENUM('queued', 'processing', 'completed', 'failed') DEFAULT 'queued',
    attempts INT DEFAULT 0,
    error_message TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    started_at TIMESTAMP NULL DEFAULT NULL,
    completed_at TIMESTAMP NULL DEFAULT NULL,
    FOREIGN KEY (target_id) REFERENCES backup_targets(id) ON DELETE CASCADE,
    INDEX idx_status_priority (status, priority),
    INDEX idx_user (user)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Add permissions for backup management
INSERT INTO permissions (name, description) VALUES
    ('backup_manage_global', 'Manage global backup targets'),
    ('backup_view_all', 'View all user backups'),
    ('backup_download_all', 'Download all user backups'),
    ('backup_delete_all', 'Delete all user backups'),
    ('backup_manage_own', 'Manage own backup targets'),
    ('backup_create', 'Create backups'),
    ('backup_download_own', 'Download own backups'),
    ('backup_delete_own', 'Delete own backups')
ON DUPLICATE KEY UPDATE description = VALUES(description);

-- Grant backup permissions to root
INSERT INTO user_permissions (username, permission_id)
SELECT 'root', id FROM permissions WHERE name IN (
    'backup_manage_global',
    'backup_view_all',
    'backup_download_all',
    'backup_delete_all',
    'backup_manage_own',
    'backup_create',
    'backup_download_own',
    'backup_delete_own'
)
ON DUPLICATE KEY UPDATE username = VALUES(username);

-- Rollback procedure
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS rollback_backup_system()
BEGIN
    -- Remove permissions
    DELETE FROM user_permissions WHERE permission_id IN (
        SELECT id FROM permissions WHERE name LIKE 'backup_%'
    );
    DELETE FROM permissions WHERE name LIKE 'backup_%';
    
    -- Drop tables in correct order
    DROP TABLE IF EXISTS backup_queue;
    DROP TABLE IF EXISTS backup_schedules;
    DROP TABLE IF EXISTS backup_history;
    DROP TABLE IF EXISTS backup_targets;
END//
DELIMITER ;