-- Extensions
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- Tables

CREATE TABLE IF NOT EXISTS users (
  id BIGSERIAL PRIMARY KEY,
  user_name TEXT NOT NULL UNIQUE,
  display_name TEXT NOT NULL,
  pw_hash BYTEA NOT NULL,
  email_address TEXT NOT NULL,
  enabled BOOLEAN NOT NULL DEFAULT TRUE,
  created TIMESTAMP DEFAULT NOW() NOT NULL
);

CREATE TABLE IF NOT EXISTS files (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  description TEXT,
  mimetype TEXT NOT NULL,
  size BIGINT NOT NULL,
  blake2 BYTEA NOT NULL UNIQUE,
  score DECIMAL,
  creator BIGINT REFERENCES users (id),
  created TIMESTAMP DEFAULT NOW() NOT NULL,
  updated TIMESTAMP DEFAULT NOW() NOT NULL
);

CREATE TABLE IF NOT EXISTS processing_jobs (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  created TIMESTAMP DEFAULT NOW() NOT NULL,
  started TIMESTAMP,
  completed TIMESTAMP,
  status TEXT,
  job_type TEXT,
  error TEXT,
  messages TEXT[]
);

CREATE TABLE IF NOT EXISTS diec (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  data JSONB,
  created TIMESTAMP DEFAULT NOW() NOT NULL
);

CREATE TABLE IF NOT EXISTS msoffice (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  verdict TEXT DEFAULT 'pending',
  container_format TEXT,
  encrypted BOOLEAN DEFAULT false,
  file_format TEXT,
  vba_macros TEXT,
  xlm_macros TEXT,
  vba_stomping BOOLEAN DEFAULT false,
  nb_autoexec INTEGER,
  nb_iocs INTEGER,
  nb_macros INTEGER,
  nb_suspicious INTEGER,
  olevba_results TEXT[][],
  macros TEXT[][],
  created TIMESTAMP DEFAULT NOW() NOT NULL
);


CREATE TABLE IF NOT EXISTS file_properties (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  sha256 BYTEA,
  md5 BYTEA,
  libmagic_mime TEXT,
  libmagic_extension TEXT,
  libmagic_apple TEXT,
  created TIMESTAMP DEFAULT NOW() NOT NULL
);

CREATE TABLE IF NOT EXISTS yara_results (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  matched TEXT[],
  created TIMESTAMP DEFAULT NOW() NOT NULL
);

CREATE TABLE IF NOT EXISTS capa_results (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  data JSONB,
  type TEXT DEFAULT 'default' NOT NULL,
  created TIMESTAMP DEFAULT NOW() NOT NULL
);

-- Indices
-- Since tables will be heavily accessed by file_id, there should be indices for them
CREATE INDEX idx_diec_file_id ON diec (file_id);
CREATE INDEX idx_processing_jobs_file_id ON processing_jobs (file_id);
CREATE INDEX idx_msoffice_results_file_id ON msoffice (file_id);
CREATE INDEX idx_file_properties_file_id ON file_properties (file_id);
CREATE INDEX idx_file_id ON files (id);
CREATE INDEX idx_yara_results_file_id ON yara_results (file_id);
CREATE INDEX idx_user_name ON users (user_name);
CREATE INDEX idx_capa_results_file_id ON capa_results (file_id);
