CREATE DATABASE IF NOT EXISTS emergency_tracker CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE emergency_tracker;

CREATE TABLE IF NOT EXISTS 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
);

CREATE TABLE IF NOT EXISTS 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")
INSERT IGNORE INTO users (national_id, password, name, is_admin, must_change_password) 
VALUES ('123456782', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBdXzz.JrKIFHy', 'מנהל מערכת', TRUE, FALSE);
