-- Backup System Schema
-- Creates tables for managing database backups

CREATE TABLE IF NOT EXISTS admin_panel.backups (
  id INT AUTO_INCREMENT PRIMARY KEY,
  filename VARCHAR(255) NOT NULL,
  file_path VARCHAR(512) NOT NULL,
  file_size BIGINT NOT NULL DEFAULT 0,
  backup_type ENUM('manual', 'scheduled') NOT NULL DEFAULT 'manual',
  status ENUM('pending', 'in_progress', 'completed', 'failed') NOT NULL DEFAULT 'pending',
  databases TEXT,  -- JSON array of backed up databases
  compressed BOOLEAN DEFAULT TRUE,
  encrypted BOOLEAN DEFAULT FALSE,
  encryption_key VARCHAR(255),
  checksum VARCHAR(64),  -- SHA-256 checksum for integrity
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  created_by VARCHAR(100) DEFAULT 'admin',
  expires_at TIMESTAMP NULL,
  error_message TEXT,
  metadata JSON,  -- Additional backup metadata
  INDEX idx_created_at (created_at),
  INDEX idx_status (status),
  INDEX idx_backup_type (backup_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Backup schedules table
CREATE TABLE IF NOT EXISTS admin_panel.backup_schedules (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  schedule_type ENUM('daily', 'weekly', 'monthly') NOT NULL,
  schedule_time TIME NOT NULL,
  schedule_day INT,  -- Day of week (0-6) for weekly, day of month (1-31) for monthly
  databases TEXT,  -- JSON array of databases to backup
  retention_count INT DEFAULT 7,  -- Keep last N backups
  enabled BOOLEAN DEFAULT TRUE,
  compressed BOOLEAN DEFAULT TRUE,
  encrypted BOOLEAN DEFAULT FALSE,
  last_run_at TIMESTAMP NULL,
  next_run_at TIMESTAMP NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  metadata JSON,
  INDEX idx_enabled (enabled),
  INDEX idx_next_run (next_run_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Backup settings table
CREATE TABLE IF NOT EXISTS admin_panel.backup_settings (
  id INT AUTO_INCREMENT PRIMARY KEY,
  setting_key VARCHAR(100) NOT NULL UNIQUE,
  setting_value TEXT,
  description TEXT,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Insert default settings
INSERT INTO admin_panel.backup_settings (setting_key, setting_value, description) VALUES
('backup_path', '/app/backups', 'Directory where backups are stored'),
('max_retention_days', '30', 'Maximum days to keep backups'),
('compression_enabled', 'true', 'Enable gzip compression for backups'),
('encryption_enabled', 'false', 'Enable encryption for backups'),
('cloud_storage_enabled', 'false', 'Enable cloud storage upload'),
('cloud_storage_provider', 's3', 'Cloud storage provider (s3, gcs, azure)'),
('cloud_storage_bucket', '', 'Cloud storage bucket name')
ON DUPLICATE KEY UPDATE setting_value = setting_value;
