-- Geofeed Manager Database Schema
-- For MariaDB/MySQL

CREATE DATABASE IF NOT EXISTS geofeed_manager;
USE geofeed_manager;

-- Main geofeed entries table
CREATE TABLE IF NOT EXISTS geofeed_entries (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ip_prefix VARCHAR(50) NOT NULL,
    country_code CHAR(2) DEFAULT NULL,
    region_code VARCHAR(10) DEFAULT NULL,
    city VARCHAR(255) DEFAULT NULL,
    postal_code VARCHAR(50) DEFAULT NULL,
    notes TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_prefix (ip_prefix),
    INDEX idx_country (country_code),
    INDEX idx_region (region_code),
    INDEX idx_city (city)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Audit log for tracking changes
CREATE TABLE IF NOT EXISTS geofeed_audit_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    entry_id INT,
    action ENUM('INSERT', 'UPDATE', 'DELETE') NOT NULL,
    old_values JSON DEFAULT NULL,
    new_values JSON DEFAULT NULL,
    changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    changed_by VARCHAR(255) DEFAULT NULL,
    INDEX idx_entry (entry_id),
    INDEX idx_action (action),
    INDEX idx_changed_at (changed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Settings table for app configuration
CREATE TABLE IF NOT EXISTS geofeed_settings (
    setting_key VARCHAR(100) PRIMARY KEY,
    setting_value TEXT,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Insert default settings
INSERT INTO geofeed_settings (setting_key, setting_value) VALUES
('bunny_cdn_storage_zone', ''),
('bunny_cdn_api_key', ''),
('bunny_cdn_file_path', '/geofeed.csv'),
('last_export_at', NULL)
ON DUPLICATE KEY UPDATE setting_key = setting_key;
