-- Database Schema untuk Motion Path System

CREATE DATABASE IF NOT EXISTS motion_paths CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE motion_paths;

-- Table untuk admin login
CREATE TABLE IF NOT EXISTS admins (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    email VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_login TIMESTAMP NULL,
    INDEX idx_username (username)
) ENGINE=InnoDB;

-- Insert default admin (password: admin123)
INSERT INTO admins (username, password, email) VALUES 
('admin', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'admin@motion.local');

-- Table untuk paths metadata
CREATE TABLE IF NOT EXISTS paths (
    id INT AUTO_INCREMENT PRIMARY KEY,
    place_id BIGINT NOT NULL,
    parent_place_id BIGINT DEFAULT NULL,
    map_version INT NOT NULL DEFAULT 1,
    is_checkpoint BOOLEAN DEFAULT FALSE,
    checkpoint_index INT DEFAULT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size INT DEFAULT 0,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    downloads INT DEFAULT 0,
    uploader_id BIGINT DEFAULT NULL,
    uploader_name VARCHAR(100),
    notes TEXT,
    INDEX idx_place_id (place_id),
    INDEX idx_map_version (map_version),
    INDEX idx_checkpoint (is_checkpoint, checkpoint_index),
    INDEX idx_upload_date (upload_date)
) ENGINE=InnoDB;

-- Table untuk tracking downloads
CREATE TABLE IF NOT EXISTS download_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    path_id INT NOT NULL,
    user_id BIGINT,
    username VARCHAR(100),
    download_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    ip_address VARCHAR(45),
    FOREIGN KEY (path_id) REFERENCES paths(id) ON DELETE CASCADE,
    INDEX idx_path_id (path_id),
    INDEX idx_download_date (download_date)
) ENGINE=InnoDB;

-- Table untuk API keys (opsional, untuk security)
CREATE TABLE IF NOT EXISTS api_keys (
    id INT AUTO_INCREMENT PRIMARY KEY,
    api_key VARCHAR(64) UNIQUE NOT NULL,
    description VARCHAR(255),
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_used TIMESTAMP NULL,
    INDEX idx_api_key (api_key)
) ENGINE=InnoDB;

-- Insert default API key
INSERT INTO api_keys (api_key, description) VALUES 
('motion_api_key_2024_secure_token_change_this', 'Default API Key - Please Change!');
