CREATE EXTENSION IF NOT EXISTS "pgcrypto";

CREATE TABLE IF NOT EXISTS "users" (
  id BIGSERIAL PRIMARY KEY,
  username VARCHAR(20) UNIQUE NOT NULL,
  verified BOOLEAN DEFAULT FALSE,
  registration_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  deleted BOOLEAN DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS "banned_users" (
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  reason VARCHAR(512),
  expires_at TIMESTAMP,
  banned_by VARCHAR(20) DEFAULT 'system',
  pardoned BOOLEAN DEFAULT FALSE,
  pardoned_by VARCHAR(20)
);

CREATE TABLE IF NOT EXISTS "login_informations"  (
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  email VARCHAR(75) UNIQUE,
  password_hash VARCHAR(512) NOT NULL,
  totp_encrypted VARCHAR(512),
  email_2fa_enabled BOOLEAN DEFAULT FALSE,
  password_change_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS "confirmation_codes" (
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  code_type INTEGER NOT NULL CHECK (code_type IN (0, 1)),
  code_hash VARCHAR(512) NOT NULL,
  expires_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + INTERVAL '10 minutes',
  used BOOLEAN DEFAULT FALSE,
  deleted BOOLEAN DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS "sessions" (
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  guid UUID NOT NULL DEFAULT gen_random_uuid(),
  name VARCHAR(100),
  platform VARCHAR(32),
  latest_ip VARCHAR(16),
  login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_seen_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  terminated BOOLEAN DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS "profiles" (
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  name VARCHAR(75) NOT NULL,
  bio VARCHAR(512),
  avatar_url VARCHAR(255),
  birthday TIMESTAMP,
  color VARCHAR(7),
  color_grad VARCHAR(7)
);

CREATE TABLE IF NOT EXISTS "profile_settings" (
  id BIGSERIAL PRIMARY KEY,
  profile_id BIGINT UNIQUE NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
  hide_fulfilled BOOLEAN DEFAULT TRUE,
  hide_profile_details BOOLEAN DEFAULT FALSE,
  hide_for_unauthenticated BOOLEAN DEFAULT FALSE,
  hide_birthday BOOLEAN DEFAULT FALSE,
  hide_dates BOOLEAN DEFAULT FALSE,
  captcha BOOLEAN DEFAULT FALSE,
  followers_only_interaction BOOLEAN DEFAULT FALSE
)
