-- Installation registry: tracks GitHub App installations and indexing jobs.

CREATE TABLE IF NOT EXISTS gh_installations (
    id              BIGSERIAL PRIMARY KEY,
    installation_id BIGINT NOT NULL UNIQUE,
    org_login       TEXT NOT NULL,
    org_id          BIGINT NOT NULL DEFAULT 0,
    app_id          TEXT NOT NULL DEFAULT '',
    status          TEXT NOT NULL DEFAULT 'active',
    installed_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_indexed_at TIMESTAMPTZ,
    repos_count     INT NOT NULL DEFAULT 0,
    auth0_org_id    TEXT NOT NULL DEFAULT ''
);

CREATE INDEX IF NOT EXISTS idx_gh_installations_org_login ON gh_installations (org_login);
CREATE INDEX IF NOT EXISTS idx_gh_installations_status ON gh_installations (status);

-- Migration: add auth0_org_id column if missing (must run before the index below).
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'gh_installations' AND column_name = 'auth0_org_id'
    ) THEN
        ALTER TABLE gh_installations ADD COLUMN auth0_org_id TEXT NOT NULL DEFAULT '';
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_gh_installations_auth0_org_id ON gh_installations (auth0_org_id);

CREATE TABLE IF NOT EXISTS index_jobs (
    id              BIGSERIAL PRIMARY KEY,
    installation_id BIGINT NOT NULL,
    repo            TEXT NOT NULL,
    status          TEXT NOT NULL DEFAULT 'pending',
    started_at      TIMESTAMPTZ,
    completed_at    TIMESTAMPTZ,
    specs_indexed   INT NOT NULL DEFAULT 0,
    errors          INT NOT NULL DEFAULT 0,
    error_message   TEXT NOT NULL DEFAULT ''
);

CREATE INDEX IF NOT EXISTS idx_index_jobs_installation_id ON index_jobs (installation_id);
CREATE INDEX IF NOT EXISTS idx_index_jobs_status ON index_jobs (status);
CREATE INDEX IF NOT EXISTS idx_index_jobs_repo ON index_jobs (repo);
