-- 홈 관리 시스템 데이터베이스 초기 설정

-- 데이터베이스 생성 (Docker에서 자동 생성되므로 주석 처리)
-- CREATE DATABASE home_management CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- USE home_management;

-- 1. 디바이스 관리 테이블
CREATE TABLE devices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    device_id VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    device_type ENUM('server', 'nas', 'router', 'smart_plug', 'other') NOT NULL,
    location VARCHAR(50),
    ip_address VARCHAR(45),
    mac_address VARCHAR(17),
    power_rating_watts INT,
    monitoring_enabled BOOLEAN DEFAULT TRUE,
    metadata JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_device_id (device_id),
    INDEX idx_type_enabled (device_type, monitoring_enabled)
) ENGINE=InnoDB;

-- 2. 전력 소비 데이터 테이블
CREATE TABLE power_consumption (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    device_id VARCHAR(50) NOT NULL,
    timestamp TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP(3),
    watts DECIMAL(8,2) NOT NULL,
    voltage DECIMAL(6,2),
    current DECIMAL(6,3),
    kwh_total DECIMAL(10,4),
    metadata JSON,
    INDEX idx_device_time (device_id, timestamp),
    INDEX idx_timestamp (timestamp),
    INDEX idx_watts (watts),
    FOREIGN KEY (device_id) REFERENCES devices(device_id) ON DELETE CASCADE
) ENGINE=InnoDB
PARTITION BY RANGE (UNIX_TIMESTAMP(timestamp)) (
    PARTITION p_2025_q1 VALUES LESS THAN (UNIX_TIMESTAMP('2025-04-01')),
    PARTITION p_2025_q2 VALUES LESS THAN (UNIX_TIMESTAMP('2025-07-01')),
    PARTITION p_2025_q3 VALUES LESS THAN (UNIX_TIMESTAMP('2025-10-01')),
    PARTITION p_2025_q4 VALUES LESS THAN (UNIX_TIMESTAMP('2026-01-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
);

-- 3. 네트워크 트래픽 테이블
CREATE TABLE network_traffic (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    device_mac VARCHAR(17) NOT NULL,
    device_name VARCHAR(100),
    timestamp TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP(3),
    bytes_in BIGINT UNSIGNED NOT NULL,
    bytes_out BIGINT UNSIGNED NOT NULL,
    packets_in INT UNSIGNED,
    packets_out INT UNSIGNED,
    connection_count INT UNSIGNED,
    metadata JSON,
    INDEX idx_mac_time (device_mac, timestamp),
    INDEX idx_timestamp (timestamp)
) ENGINE=InnoDB;

-- 4. 시스템 리소스 테이블
CREATE TABLE system_resources (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    server_name VARCHAR(50) NOT NULL,
    timestamp TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP(3),
    cpu_percent DECIMAL(5,2),
    memory_used_gb DECIMAL(6,2),
    memory_total_gb DECIMAL(6,2),
    disk_used_gb DECIMAL(8,2),
    disk_total_gb DECIMAL(8,2),
    network_io JSON,
    temperature DECIMAL(4,1),
    load_average JSON,
    processes_count INT,
    uptime_seconds BIGINT,
    INDEX idx_server_time (server_name, timestamp)
) ENGINE=InnoDB;

-- 5. 서비스 상태 테이블
CREATE TABLE service_status (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    service_name VARCHAR(50) NOT NULL,
    server_name VARCHAR(50) NOT NULL,
    timestamp TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP(3),
    status ENUM('online', 'offline', 'degraded', 'maintenance') NOT NULL,
    response_time_ms INT UNSIGNED,
    cpu_usage DECIMAL(5,2),
    memory_usage_mb INT,
    error_message TEXT,
    metadata JSON,
    INDEX idx_service_time (service_name, timestamp),
    INDEX idx_server_service (server_name, service_name),
    INDEX idx_status (status, timestamp)
) ENGINE=InnoDB;

-- 6. 사용자 관리 테이블
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE,
    password_hash VARCHAR(255),
    full_name VARCHAR(100),
    role ENUM('admin', 'family', 'guest') DEFAULT 'family',
    preferences JSON,
    last_login TIMESTAMP NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_username (username),
    INDEX idx_email (email),
    INDEX idx_role (role)
) ENGINE=InnoDB;

-- 7. 알림 규칙 테이블
CREATE TABLE alert_rules (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    condition_type ENUM('threshold', 'change', 'pattern', 'custom') NOT NULL,
    target_table VARCHAR(50) NOT NULL,
    target_field VARCHAR(50) NOT NULL,
    operator ENUM('>', '<', '>=', '<=', '=', '!=', 'contains') NOT NULL,
    threshold_value DECIMAL(15,4),
    time_window_minutes INT DEFAULT 5,
    severity ENUM('info', 'warning', 'critical') DEFAULT 'warning',
    notification_methods JSON,
    is_active BOOLEAN DEFAULT TRUE,
    cooldown_minutes INT DEFAULT 60,
    last_triggered TIMESTAMP NULL,
    created_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES users(id),
    INDEX idx_active (is_active),
    INDEX idx_target (target_table, target_field)
) ENGINE=InnoDB;

-- 8. 알림 로그 테이블
CREATE TABLE alert_logs (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    alert_rule_id INT NOT NULL,
    triggered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    trigger_value DECIMAL(15,4),
    message TEXT,
    severity ENUM('info', 'warning', 'critical') NOT NULL,
    notification_sent BOOLEAN DEFAULT FALSE,
    resolved_at TIMESTAMP NULL,
    metadata JSON,
    FOREIGN KEY (alert_rule_id) REFERENCES alert_rules(id) ON DELETE CASCADE,
    INDEX idx_rule_time (alert_rule_id, triggered_at),
    INDEX idx_severity (severity, triggered_at)
) ENGINE=InnoDB;

-- 기본 관리자 사용자 생성 (패스워드는 'admin123')
INSERT INTO users (username, email, password_hash, full_name, role) VALUES
('admin', 'admin@home.local', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewsF5ckPG6Y4TZsG', '시스템 관리자', 'admin'),
('family', 'family@home.local', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewsF5ckPG6Y4TZsG', '가족 사용자', 'family');

-- 기본 디바이스 등록
INSERT INTO devices (device_id, name, device_type, location, monitoring_enabled) VALUES
('mac_mini_m4', 'Mac Mini M4 Pro', 'server', '서재', TRUE),
('ds1525plus', 'Synology DS1525+', 'nas', '서재', TRUE),
('rt6600ax', 'Synology RT6600ax', 'router', '거실', TRUE);

-- 기본 알림 규칙
INSERT INTO alert_rules (name, description, condition_type, target_table, target_field, operator, threshold_value, severity, notification_methods, created_by) VALUES
('높은 CPU 사용률', 'CPU 사용률이 80% 이상일 때 알림', 'threshold', 'system_resources', 'cpu_percent', '>', 80.0, 'warning', '["email"]', 1),
('높은 전력 소비', '전력 소비가 평소보다 50% 이상 증가했을 때', 'change', 'power_consumption', 'watts', '>', 50.0, 'warning', '["email"]', 1),
('서비스 다운', '서비스가 오프라인 상태일 때', 'threshold', 'service_status', 'status', '=', 'offline', 'critical', '["email", "push"]', 1);

-- 성능 모니터링용 뷰
CREATE VIEW device_power_summary AS
SELECT 
    d.device_id,
    d.name,
    d.device_type,
    AVG(pc.watts) as avg_watts,
    MAX(pc.watts) as max_watts,
    COUNT(*) as reading_count,
    MAX(pc.timestamp) as last_reading
FROM devices d
LEFT JOIN power_consumption pc ON d.device_id = pc.device_id
WHERE d.monitoring_enabled = TRUE
GROUP BY d.device_id, d.name, d.device_type;

CREATE VIEW system_health_summary AS
SELECT 
    server_name,
    AVG(cpu_percent) as avg_cpu,
    AVG(memory_used_gb / memory_total_gb * 100) as avg_memory_pct,
    AVG(disk_used_gb / disk_total_gb * 100) as avg_disk_pct,
    MAX(timestamp) as last_update
FROM system_resources
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
GROUP BY server_name; 