-- Mysql schema

-- Enter the mysql container
-- sudo docker exec -it eegsac mysql -u root --password=123456789 educa7ls_plataforma

-- docker run --name eegsac -e MYSQL_ROOT_PASSWORD=123456789 -p 3306:3306 -d mysql:8.0-debian

CREATE TABLE person (
    person_id INTEGER PRIMARY KEY AUTO_INCREMENT,
    person_dni VARCHAR(8) NOT NULL,
    person_names VARCHAR(50) NOT NULL,
    person_paternal_surname VARCHAR(30) NOT NULL,
    person_maternal_surname VARCHAR(30) NOT NULL,
    person_classroom_id INTEGER DEFAULT -1,
    person_classroom_username VARCHAR(30) NULL DEFAULT NULL,
);

-- Add person_classroom_username
ALTER TABLE `person` ADD `person_classroom_username` VARCHAR(30) NULL DEFAULT NULL AFTER `person_classroom_id`; 


CREATE TABLE course (
    course_id INTEGER PRIMARY KEY AUTO_INCREMENT,
    course_name VARCHAR(50) NOT NULL,
    course_display_name VARCHAR(100) NOT NULL,
    course_days_amount INTEGER NOT NULL,
    course_has_custom_label BOOLEAN NOT NULL
);

CREATE TABLE register (
    register_id INTEGER PRIMARY KEY AUTO_INCREMENT,
    register_code INTEGER NOT NULL,
    register_creation_date DATETIME NOT NULL,
    register_display_date DATETIME NOT NULL,
    register_custom_label INTEGER NOT NULL,
    register_is_preview BOOLEAN NOT NULL,
    register_person_id INTEGER NOT NULL,
    register_course_id INTEGER NOT NULL,

    FOREIGN KEY (register_person_id) REFERENCES person (person_id),
    FOREIGN KEY (register_course_id) REFERENCES course (course_id),

    CONSTRAINT fk_register_custom_label
    FOREIGN KEY (register_custom_label) 
    REFERENCES custom_label(custom_label_id)
);

CREATE TABLE custom_label (
    custom_label_id INTEGER PRIMARY KEY AUTO_INCREMENT,
    custom_label_value VARCHAR(50) NOT NULL
);


-- Migration

-- Empty label
INSERT INTO custom_label (custom_label_value) VALUES ('');

ALTER TABLE register MODIFY COLUMN register_custom_label INTEGER NOT NULL DEFAULT 1;

-- Set all registers by default to empty label
UPDATE register SET register_custom_label = 1;

-- Add constraint after all values are set to empty label
ALTER TABLE register ADD CONSTRAINT fk_register_custom_label
    FOREIGN KEY (register_custom_label) 
    REFERENCES custom_label(custom_label_id);

-- End migration
