-- Geonet project search — Fase 1 metadata (PostgreSQL 10.100.1.25)
-- Jalankan sebagai postgres superuser.

CREATE EXTENSION IF NOT EXISTS pg_trgm;

DO $$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'geonet_project') THEN
        CREATE ROLE geonet_project LOGIN PASSWORD 'CHANGE_ME_ON_DEPLOY';
    END IF;
END
$$;

SELECT 'CREATE DATABASE geonet_project_search OWNER geonet_project'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'geonet_project_search')\gexec

GRANT ALL PRIVILEGES ON DATABASE geonet_project_search TO geonet_project;

\connect geonet_project_search

CREATE EXTENSION IF NOT EXISTS pg_trgm;

GRANT ALL ON SCHEMA public TO geonet_project;

CREATE TABLE IF NOT EXISTS project_index (
    id              BIGSERIAL PRIMARY KEY,
    source_id       VARCHAR(64) NOT NULL,
    relative_path   TEXT NOT NULL,
    full_smb_path   TEXT NOT NULL,
    client_name     VARCHAR(255),
    year_folder     SMALLINT,
    is_directory    BOOLEAN NOT NULL DEFAULT true,
    file_ext        VARCHAR(16),
    size_bytes      BIGINT,
    mtime           TIMESTAMPTZ,
    indexed_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (source_id, relative_path)
);

CREATE INDEX IF NOT EXISTS idx_project_index_client
    ON project_index USING gin (client_name gin_trgm_ops);

CREATE INDEX IF NOT EXISTS idx_project_index_source_year
    ON project_index (source_id, year_folder);

CREATE INDEX IF NOT EXISTS idx_project_index_mtime
    ON project_index (mtime DESC);

CREATE TABLE IF NOT EXISTS project_index_runs (
    id              BIGSERIAL PRIMARY KEY,
    source_id       VARCHAR(64) NOT NULL,
    started_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    finished_at     TIMESTAMPTZ,
    status          VARCHAR(32) NOT NULL DEFAULT 'running',
    rows_upserted   BIGINT NOT NULL DEFAULT 0,
    error_message   TEXT
);

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO geonet_project;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO geonet_project;
