CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE repositories (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name        TEXT NOT NULL UNIQUE,
    owner       TEXT NOT NULL,
    forgejo_url TEXT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE commits (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    repository_id   UUID NOT NULL REFERENCES repositories(id),
    sha             TEXT NOT NULL,
    author          TEXT,
    message         TEXT,
    branch          TEXT,
    committed_at    TIMESTAMPTZ,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (repository_id, sha)
);

CREATE INDEX idx_commits_repo_sha ON commits (repository_id, sha);

CREATE TABLE builds (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    repository_id   UUID NOT NULL REFERENCES repositories(id),
    commit_id       UUID NOT NULL REFERENCES commits(id),
    builder         TEXT,
    build_flags     TEXT,
    tags            JSONB DEFAULT '{}',
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_builds_commit ON builds (commit_id);

CREATE TABLE artifacts (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    repository_id   UUID NOT NULL REFERENCES repositories(id),
    commit_id       UUID NOT NULL REFERENCES commits(id),
    build_id        UUID REFERENCES builds(id),
    type            TEXT NOT NULL,
    blob_key        TEXT NOT NULL,
    blob_size       BIGINT NOT NULL,
    crash_message   TEXT,
    stack_trace     TEXT,
    tags            JSONB DEFAULT '{}',
    metadata        JSONB DEFAULT '{}',
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_artifacts_repo ON artifacts (repository_id);
CREATE INDEX idx_artifacts_commit ON artifacts (commit_id);
CREATE INDEX idx_artifacts_type ON artifacts (type);
CREATE INDEX idx_artifacts_created ON artifacts (created_at DESC);
