-- SIDEL ScriptsManager PostgreSQL Default Data
-- This script inserts default data for the application

-- Default admin user (password should be changed after first login)
-- Note: This will be handled by the application's init_db.py script
-- The password hash below corresponds to 'admin123' - CHANGE IN PRODUCTION

-- Default application settings
-- INSERT INTO settings (key, value, description) VALUES 
-- ('app_version', '1.0.0', 'Application version'),
-- ('backup_enabled', 'true', 'Enable automatic backups'),
-- ('max_projects_per_user', '50', 'Maximum projects per user'),
-- ('default_theme', 'light', 'Default UI theme'),
-- ('default_language', 'en', 'Default interface language')
-- ON CONFLICT (key) DO NOTHING;

-- Default script categories/tags
-- INSERT INTO script_categories (name, description) VALUES 
-- ('analysis', 'Data analysis scripts'),
-- ('automation', 'Process automation scripts'),
-- ('reporting', 'Report generation scripts'),
-- ('maintenance', 'System maintenance scripts'),
-- ('development', 'Development and testing scripts')
-- ON CONFLICT (name) DO NOTHING;

-- PostgreSQL-specific maintenance tasks
-- Create a function to clean up old execution logs
CREATE OR REPLACE FUNCTION cleanup_old_execution_logs(retention_days INTEGER DEFAULT 30)
RETURNS INTEGER AS $$
DECLARE
    deleted_count INTEGER;
BEGIN
    DELETE FROM execution_logs 
    WHERE timestamp < (CURRENT_DATE - INTERVAL '1 day' * retention_days);
    
    GET DIAGNOSTICS deleted_count = ROW_COUNT;
    
    RETURN deleted_count;
END;
$$ LANGUAGE plpgsql;

-- Comment the function
COMMENT ON FUNCTION cleanup_old_execution_logs(INTEGER) IS 'Cleans up execution logs older than specified days';

-- Create a function to get database statistics
CREATE OR REPLACE FUNCTION get_database_stats()
RETURNS TABLE (
    table_name TEXT,
    row_count BIGINT,
    table_size TEXT
) AS $$
BEGIN
    RETURN QUERY
    SELECT 
        schemaname||'.'||tablename as table_name,
        n_tup_ins - n_tup_del as row_count,
        pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as table_size
    FROM pg_stat_user_tables 
    ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
END;
$$ LANGUAGE plpgsql;

-- Comment the function
COMMENT ON FUNCTION get_database_stats() IS 'Returns statistics about database tables and sizes';