/*
 * advotracker - Hotline tackingtool for Advocats
 *
 * Copyright 2019 Ralf Zerres <ralf.zerres@networkx.de>
 * SPDX-License-Identifier: (0BSD, MIT)
 */

-- sqlite3 advotracker.db \
--	.read advotracker_sqlite.sql

CREATE TABLE IF NOT EXISTS users
(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  last_name VARCHAR,
  first_name VARCHAR,
  alias VARCHAR,
  email VARCHAR,
  /* email_confirmed boolean NOT NULL DEFAULT 0, */
  email_confirmed INTEGER NOT NULL DEFAULT 0,
  password_hash VARCHAR,
  initials VARCHAR,
  date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  date_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

  -- Constraints
  CONSTRAINT users_ck_email_confirmed CHECK (email_confirmed IN (0,1))
);

CREATE INDEX IF NOT EXISTS users_ix_email ON users (email);

CREATE TABLE IF NOT EXISTS user_roles(
	id INTEGER PRIMARY KEY AUTOINCREMENT,
	name VARCHAR,
	-- Constraints
	CONSTRAINT user_roles_uk_name UNIQUE (name));

CREATE TABLE IF NOT EXISTS user_user_roles (
	user_id INTEGER NOT NULL,
	role_id INTEGER NOT NULL,
	-- Constraints
	CONSTRAINT user_user_roles_pk_user_id_role_id PRIMARY KEY (user_id, role_id),
	CONSTRAINT user_user_roles_fk_user_id FOREIGN KEY (user_id)
		   REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE,
	CONSTRAINT user_user_roles_fk_role_id FOREIGN KEY (role_id)
		   REFERENCES user_roles (id) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE INDEX IF NOT EXISTS user_user_roles_ix_user_id ON user_user_roles (user_id);
CREATE INDEX IF NOT EXISTS user_user_roles_ix_role_id ON user_user_roles (role_id);

CREATE VIEW IF NOT EXISTS view_user_roles
    AS SELECT
    users.user_id AS user_id,
    users.last_name AS last_name,
    users.first_name AS first_name,
    users.email AS email,
    users.user_initials AS initials,
    users_role.user_rolename AS role_name
    FROM user_user_roles
    INNER JOIN users ON users.user_id = user_user_roles.user_id
    INNER JOIN user_roles ON user_roles.id = user_user_roles.role_id;

CREATE TABLE IF NOT EXISTS user_claims (
       id INTEGER PRIMARY KEY AUTOINCREMENT,
       user_id INTEGER,
       type VARCHAR,
       value VARCHAR,
       -- CONSTRAINTS
       CONSTRAINT user_claims_fk_user_id FOREIGN KEY (user_id)
	       REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE INDEX IF NOT EXISTS user_claims_ix_user_id ON user_claims (user_id);

CREATE TABLE IF NOT EXISTS harms (
	id INTEGER primary key AUTOINCREMENT,
	number_harm VARCHAR,
	number_policyholder VARCHAR,
	number_callback VARCHAR,
	date_fallback TIMESTAMP,
	date_recording TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	user_id INTEGER NOT NULL,
	date_changed TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	user_id_changed INTEGER);
CREATE INDEX IF NOT EXISTS harms_ix_number_harm ON harms (number_harm);
