CREATE EXTENSION IF NOT EXISTS pg_trgm;

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;
