-- Use the emergency_tracker database
USE emergency_tracker;

-- Drop existing tables if they exist (for clean setup)
DROP TABLE IF EXISTS admin_actions;
DROP TABLE IF EXISTS users;

-- Create users table with all required fields
CREATE TABLE users (
    national_id CHAR(9) PRIMARY KEY,
    password VARCHAR(255) NOT NULL,
    name VARCHAR(100) NOT NULL,
    in_shelter ENUM('yes', 'no', 'no_alarm') DEFAULT NULL,
    last_updated DATETIME DEFAULT NULL,
    is_admin BOOLEAN NOT NULL DEFAULT FALSE,
    must_change_password BOOLEAN NOT NULL DEFAULT TRUE,
    password_changed_at DATETIME DEFAULT NULL,
    department ENUM('מרחב', 'מחשוב', 'אגם', 'לשכה') DEFAULT NULL,
    team ENUM('מפלג', 'אתרים', 'מערכות תקשוב', 'שובר', 'קריה', 'כס', 'סיסטם', 'תקשורת', 'נוק', 'אגם', 'לשכה') DEFAULT NULL
);

-- Create admin_actions table
CREATE TABLE admin_actions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    admin_id CHAR(9) NOT NULL,
    action_type ENUM('reset_all', 'reset_password') NOT NULL,
    target_user_id CHAR(9) DEFAULT NULL,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (admin_id) REFERENCES users(national_id),
    FOREIGN KEY (target_user_id) REFERENCES users(national_id)
);

-- Insert a test admin user (password: "admin123")
-- Hash generated with bcrypt for "admin123"
INSERT INTO users (national_id, password, name, is_admin, must_change_password, department, team) 
VALUES ('123456782', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBdXzz.JrKIFHy', 'מנהל מערכת', TRUE, FALSE, 'מחשוב', 'סיסטם')
ON DUPLICATE KEY UPDATE 
    department = 'מחשוב', 
    team = 'סיסטם';

-- Show tables were created
SHOW TABLES;

-- Show the admin user was created
SELECT national_id, name, is_admin, department, team FROM users WHERE is_admin = TRUE;
