DROP TABLE IF EXISTS bloc;
DROP TABLE IF EXISTS page;
DROP TABLE IF EXISTS messages;
DROP TABLE IF EXISTS utilisateur;

CREATE TABLE utilisateur (
    id INT PRIMARY KEY AUTO_INCREMENT,
    login VARCHAR(100) NOT NULL,
    mot_de_passe VARCHAR(255) NOT NULL,
    privilege ENUM('ADMIN', 'USER', 'GUEST') NOT NULL
);

CREATE TABLE page (
    id INT PRIMARY KEY AUTO_INCREMENT,
    titre VARCHAR(200) NOT NULL,
    date_creation DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    date_modification DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    auteur_id INT NOT NULL,
    droits ENUM('LECTURE', 'ECRITURE', 'ADMIN') NOT NULL,
    FOREIGN KEY (auteur_id) REFERENCES utilisateur(id) ON DELETE CASCADE
);

CREATE TABLE bloc (
    id INT PRIMARY KEY AUTO_INCREMENT,
    type ENUM('TEXTE', 'LISTE', 'TITRE', 'CODE', 'PAGE') NOT NULL,
    contenu TEXT,
    date_creation DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    date_modification DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    page_id INT NOT NULL,
    ordre INT NOT NULL,
    auteur_id INT NOT NULL,
    metadata JSON,
    FOREIGN KEY (page_id) REFERENCES page(id) ON DELETE CASCADE,
    FOREIGN KEY (auteur_id) REFERENCES utilisateur(id) ON DELETE CASCADE
);

CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    login VARCHAR(100) NOT NULL,
    contenu TEXT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

DELIMITER //

CREATE TRIGGER trg_bloc_maj
BEFORE UPDATE ON bloc
FOR EACH ROW
BEGIN
    SET NEW.date_modification = NOW();
END;
//

DELIMITER ;

DELIMITER //

CREATE TRIGGER trg_page_maj
BEFORE UPDATE ON page
FOR EACH ROW
BEGIN
    SET NEW.date_modification = NOW();
END;
//

DELIMITER ;
