-- Migration: Create backup feature tables
-- Description: Tables for backup schedules, history, and settings

-- ============================================
-- backup_schedules - Scheduled backup configurations
-- ============================================
CREATE TABLE IF NOT EXISTS backup_schedules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) NOT NULL,
    frequency VARCHAR(20) NOT NULL CHECK (frequency IN ('hourly', 'daily', 'weekly', 'monthly')),
    cron_expression VARCHAR(50) NOT NULL,
    retention_count INTEGER NOT NULL DEFAULT 7,
    is_enabled BOOLEAN DEFAULT true,
    last_run_at TIMESTAMP WITH TIME ZONE,
    next_run_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- ============================================
-- backup_history - Record of all backup operations
-- ============================================
CREATE TABLE IF NOT EXISTS backup_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    schedule_id UUID REFERENCES backup_schedules(id) ON DELETE SET NULL,
    backup_type VARCHAR(20) NOT NULL CHECK (backup_type IN ('scheduled', 'manual')),
    filename VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size_bytes BIGINT NOT NULL,
    database_tables_count INTEGER,
    documents_count INTEGER,
    status VARCHAR(20) NOT NULL CHECK (status IN ('in_progress', 'completed', 'failed')),
    error_message TEXT,
    started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    completed_at TIMESTAMP WITH TIME ZONE,
    created_by VARCHAR(255),
    metadata JSONB DEFAULT '{}'
);

-- ============================================
-- backup_settings - Global backup configuration
-- ============================================
CREATE TABLE IF NOT EXISTS backup_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    setting_key VARCHAR(50) UNIQUE NOT NULL,
    setting_value TEXT NOT NULL,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- ============================================
-- Indexes
-- ============================================
CREATE INDEX IF NOT EXISTS idx_backup_history_status ON backup_history(status);
CREATE INDEX IF NOT EXISTS idx_backup_history_started ON backup_history(started_at DESC);
CREATE INDEX IF NOT EXISTS idx_backup_history_schedule ON backup_history(schedule_id);
CREATE INDEX IF NOT EXISTS idx_backup_schedules_enabled ON backup_schedules(is_enabled);
CREATE INDEX IF NOT EXISTS idx_backup_schedules_next_run ON backup_schedules(next_run_at);

-- ============================================
-- Triggers for updated_at
-- ============================================

-- Create update_updated_at_column function if it doesn't exist
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Trigger for backup_schedules
DROP TRIGGER IF EXISTS backup_schedules_updated_at ON backup_schedules;
CREATE TRIGGER backup_schedules_updated_at
    BEFORE UPDATE ON backup_schedules
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- Trigger for backup_settings
DROP TRIGGER IF EXISTS backup_settings_updated_at ON backup_settings;
CREATE TRIGGER backup_settings_updated_at
    BEFORE UPDATE ON backup_settings
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- ============================================
-- Default settings
-- ============================================
INSERT INTO backup_settings (setting_key, setting_value) VALUES
    ('email_on_success', 'true'),
    ('email_on_failure', 'true'),
    ('admin_email', ''),
    ('max_backup_size_mb', '1024'),
    ('compression_enabled', 'true')
ON CONFLICT (setting_key) DO NOTHING;
