DROP TABLE IF EXISTS TEAMS;
DROP TABLE IF EXISTS POSITIONS;
DROP TABLE IF EXISTS QR_CODES;
DROP TABLE IF EXISTS CIPHERS; 
DROP TABLE IF EXISTS DIFFICULTY_LEVELS;
DROP TABLE IF EXISTS TASKS;
DROP TABLE IF EXISTS ADMINS;
DROP TABLE IF EXISTS PENALTIES;

CREATE TABLE TEAMS (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    city VARCHAR(100) NOT NULL,
    difficulty_level INTEGER NOT NULL,
    password VARCHAR(255) NOT NULL,
    last_cipher INTEGER DEFAULT 0,
    penalty INTEGER DEFAULT 0,
    FOREIGN KEY (difficulty_level) REFERENCES DIFFICULTY_LEVELS(id)
);
CREATE TABLE POSITIONS (
    id INTEGER PRIMARY KEY,
    gps VARCHAR(100) NOT NULL,
    clue TEXT NOT NULL
);
CREATE TABLE QR_CODES (
    id INTEGER PRIMARY KEY,
    position_id INTEGER NOT NULL,
    uid VARCHAR(100) UNIQUE NOT NULL,
    FOREIGN KEY (position_id) REFERENCES positions(id)
);
CREATE TABLE CIPHERS (
    id INTEGER PRIMARY KEY,
    assignment TEXT NOT NULL,
    solution TEXT NOT NULL,
    clue TEXT NOT NULL
);
CREATE TABLE DIFFICULTY_LEVELS (
    id INTEGER PRIMARY KEY,
    level_name VARCHAR(100) NOT NULL
);
CREATE TABLE TASKS (
    id INTEGER PRIMARY KEY,
    cipher_id INTEGER NOT NULL,
    position_id INTEGER NOT NULL,
    difficulty_level INTEGER NOT NULL,
    order_num INTEGER NOT NULL,
    end_clue TEXT NOT NULL,
    FOREIGN KEY (cipher_id) REFERENCES CIPHERS(id),
    FOREIGN KEY (position_id) REFERENCES POSITIONS(id),
    FOREIGN KEY (difficulty_level) REFERENCES DIFFICULTY_LEVELS(id)
);
CREATE TABLE ADMINS (
    id INTEGER PRIMARY KEY,
    username VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL
);
CREATE TABLE PENALTIES (
    id INTEGER PRIMARY KEY,
    team_id INTEGER NOT NULL,
    task_id INTEGER NOT NULL,
    minutes INTEGER NOT NULL DEFAULT 0,
    FOREIGN KEY (team_id) REFERENCES TEAMS(id),
    FOREIGN KEY (task_id) REFERENCES TASKS(id)
);