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

-- Tables
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,
  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(),
  started TIMESTAMP,
  completed TIMESTAMP,
  status TEXT,
  job_type TEXT,
  error TEXT,
  messages JSONB DEFAULT '[]'::JSONB
);

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

CREATE TABLE IF NOT EXISTS msoffice_oleid (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  data JSONB
);

CREATE TABLE IF NOT EXISTS msoffice_olevba (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  data JSONB
);

CREATE TABLE IF NOT EXISTS msoffice_mraptor (
  id BIGSERIAL PRIMARY KEY,
  file_id UUID REFERENCES files (id) ON DELETE CASCADE,
  data JSONB
);

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 JSONB,
  macros JSONB
);


CREATE TABLE IF NOT EXISTS file_properties (
  id UUID PRIMARY KEY,
  sha256 BYTEA,
  md5 BYTEA,
  libmagic_mime TEXT,
  libmagic_extension TEXT,
  libmagic_apple TEXT
);

-- 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_oleid_file_id ON msoffice_oleid (file_id);
CREATE INDEX idx_msoffice_olevba_file_id ON msoffice_olevba (file_id);
CREATE INDEX idx_msoffice_mraptor_file_id ON msoffice_mraptor (file_id);
CREATE INDEX idx_msoffice_results_file_id ON msoffice_results (file_id);
CREATE INDEX idx_file_properties_id ON file_properties (id);
CREATE INDEX idx_file_id ON files (id);
