USE message_archive;

CREATE TABLE t_encyclopedia_groups (
    group_id INT PRIMARY KEY,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB CHARACTER SET utf8mb4;

CREATE TABLE t_encyclopedia_players (
    player_id INT NOT NULL,
    group_id INT NOT NULL,
    player_name VARCHAR(50) NOT NULL,
    points INT DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (player_id, group_id),
    FOREIGN KEY (group_id) REFERENCES t_encyclopedia_groups(group_id)
) ENGINE=InnoDB CHARACTER SET utf8mb4;

CREATE TABLE t_encyclopedia_active_tasks (
    active_task_id INT AUTO_INCREMENT PRIMARY KEY,
    group_id INT NOT NULL,
    question VARCHAR(255) NOT NULL,
    answer VARCHAR(100) NOT NULL,
    score INT NOT NULL,
    description TEXT,
    holder_id INT NOT NULL,
    assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    status ENUM('pending', 'completed') DEFAULT 'pending',
    FOREIGN KEY (group_id) REFERENCES t_encyclopedia_groups(group_id),
    FOREIGN KEY (holder_id, group_id) REFERENCES t_encyclopedia_players(player_id, group_id),
    INDEX (group_id)
) ENGINE=InnoDB CHARACTER SET utf8mb4;

CREATE TABLE t_encyclopedia_task_history (
    history_id INT AUTO_INCREMENT PRIMARY KEY,
    group_id INT NOT NULL,
    active_task_id INT NOT NULL,
    player_id INT NOT NULL,
    answer VARCHAR(100) NOT NULL,
    is_correct BOOLEAN DEFAULT FALSE,
    points_earned INT DEFAULT 0,
    completed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (group_id) REFERENCES t_encyclopedia_groups(group_id),
    FOREIGN KEY (active_task_id) REFERENCES t_encyclopedia_active_tasks(active_task_id),
    FOREIGN KEY (player_id, group_id) REFERENCES t_encyclopedia_players(player_id, group_id),
    INDEX (group_id)
) ENGINE=InnoDB CHARACTER SET utf8mb4;