PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS users (
  id INTEGER PRIMARY KEY,
  username VARCHAR(255) NOT NULL,
  password VARCHAR(255) NOT NULL
);

CREATE TABLE IF NOT EXISTS projects (
  id INTEGER PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  description TEXT NOT NULL,
  user_id INTEGER NOT NULL,
  FOREIGN KEY (user_id) REFERENCES users (id)
);

CREATE TABLE IF NOT EXISTS time_reports (
  id INTEGER PRIMARY KEY,
  project_id INTEGER NOT NULL,
  start DATETIME NOT NULL,
  end DATETIME NOT NULL,
  FOREIGN KEY (project_id) REFERENCES projects (id)
);

CREATE TRIGGER IF NOT EXISTS time_reports_start_before_end
  BEFORE INSERT ON time_reports
  FOR EACH ROW
  BEGIN
    SELECT
      CASE
        WHEN NEW.start >= NEW.end THEN
          RAISE (ABORT, 'start must be before end')
      END;
  END;

CREATE TABLE IF NOT EXISTS report_collection (
  id INTEGER PRIMARY KEY,
  project_id INTEGER NOT NULL,
  date DATE NOT NULL,
  signed_by INTEGER, -- NULL if not signed
  FOREIGN KEY (signed_by) REFERENCES users (id)
);

CREATE TABLE IF NOT EXISTS user_roles (
  user_id INTEGER NOT NULL,
  project_id INTEGER NOT NULL,
  role STRING NOT NULL,
  FOREIGN KEY (user_id) REFERENCES users (id)
  FOREIGN KEY (project_id) REFERENCES projects (id)
);