/*
 Mentorenwahl: A fullstack application for assigning mentors to students based on their whishes.
 Copyright (C) 2022  Dominic Grimm
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
-- +micrate Up
-- SQL in section ' Up ' is executed when this migration is applied
CREATE TYPE user_roles AS ENUM (' Teacher ', ' Student ');

CREATE TABLE users(
  id BIGSERIAL PRIMARY KEY,
  username TEXT UNIQUE NOT NULL,
  role user_roles NOT NULL,
  admin BOOLEAN NOT NULL
);

CREATE TABLE teachers(
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL UNIQUE REFERENCES users(id),
  max_students INT NOT NULL,
  skif BOOLEAN NOT NULL
);

CREATE TABLE students(
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL UNIQUE REFERENCES users(id),
  skif BOOLEAN NOT NULL
);

ALTER TABLE
  users
ADD
  COLUMN teacher_id BIGINT UNIQUE REFERENCES teachers(id);

ALTER TABLE
  users
ADD
  COLUMN student_id BIGINT UNIQUE REFERENCES students(id);

CREATE TABLE votes(
  id BIGSERIAL PRIMARY KEY,
  student_id BIGINT NOT NULL UNIQUE REFERENCES students(id)
);

ALTER TABLE
  students
ADD
  COLUMN vote_id BIGINT UNIQUE REFERENCES votes(id);

CREATE TABLE teacher_votes(
  id BIGSERIAL PRIMARY KEY,
  vote_id BIGINT NOT NULL REFERENCES votes(id),
  teacher_id BIGINT NOT NULL REFERENCES teachers(id),
  priority INT NOT NULL
);

-- +micrate Down
-- SQL section ' Down ' is executed when this migration is rolled back
DROP TABLE teacher_votes;

DROP TABLE votes;

DROP TABLE admins;

DROP TABLE teachers;

DROP TABLE students;

DROP TABLE users;

DROP TYPE user_roles;