-- Database creation
CREATE DATABASE IF NOT EXISTS proxmox_manager CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE proxmox_manager;

-- Tabella utenti
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_admin BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_login TIMESTAMP NULL,
    active BOOLEAN DEFAULT TRUE,
    INDEX idx_username (username),
    INDEX idx_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabella associazione utente-VM
CREATE TABLE IF NOT EXISTS user_vms (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    vm_id INT NOT NULL,
    vm_name VARCHAR(100),
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY unique_user_vm (user_id, vm_id),
    INDEX idx_user_id (user_id),
    INDEX idx_vm_id (vm_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabella log azioni
CREATE TABLE IF NOT EXISTS action_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    vm_id INT NOT NULL,
    action_type ENUM('start', 'stop', 'restart', 'shutdown', 'backup', 'login') NOT NULL,
    status ENUM('success', 'failed') NOT NULL,
    error_message TEXT,
    ip_address VARCHAR(45),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_vm_id (vm_id),
    INDEX idx_created_at (created_at),
    INDEX idx_action_type (action_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Crea utente admin di default
-- Username: admin
-- Password: admin123
-- IMPORTANTE: Cambia la password dopo il primo login!
-- Se il login non funziona, esegui: python reset_passwords.py
INSERT INTO users (username, email, password_hash, is_admin) 
VALUES ('admin', 'admin@localhost', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewY5NU7BqEa/5pjy', TRUE)
ON DUPLICATE KEY UPDATE username=username;

-- Esempio: crea un utente normale di test
-- Username: testuser
-- Password: test123
INSERT INTO users (username, email, password_hash, is_admin) 
VALUES ('testuser', 'test@localhost', '$2b$12$rMtoH.08EhJjXpEoE7l8/.vjL5VJ5lQdH5YQJ3TpHfNhDzJ8k8F9W', FALSE)
ON DUPLICATE KEY UPDATE username=username;

-- Esempio: assegna VM 114 all'utente test
-- INSERT INTO user_vms (user_id, vm_id, vm_name, notes) 
-- VALUES (2, 114, 'buslino-vm', 'VM di test per l\'utente');
