-- OPC schema — run once against the controlplanedb database
-- Convention: commits are linked by scanning git log for "OPC # XXXX" in the subject,
--             no separate commit table needed.

CREATE TABLE IF NOT EXISTS opc (
    id           UUID         PRIMARY KEY DEFAULT gen_random_uuid(),
    number       VARCHAR(20)  NOT NULL UNIQUE,          -- OPC # 0001
    title        VARCHAR(500) NOT NULL,
    description  TEXT         NOT NULL DEFAULT '',
    type         VARCHAR(50)  NOT NULL DEFAULT 'General',
    status       VARCHAR(50)  NOT NULL DEFAULT 'New',
    priority     VARCHAR(20)  NOT NULL DEFAULT 'Medium',
    assignee     VARCHAR(200) NOT NULL DEFAULT '',
    created_at   TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at   TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS opc_note (
    id         UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    opc_id     UUID        NOT NULL REFERENCES opc(id) ON DELETE CASCADE,
    author     VARCHAR(200) NOT NULL,
    content    TEXT        NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Artifact types: BusinessRequirement, Rule, Spec, Documentation, QaTestPath
CREATE TABLE IF NOT EXISTS opc_artifact (
    id            UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    opc_id        UUID        NOT NULL REFERENCES opc(id) ON DELETE CASCADE,
    artifact_type VARCHAR(50) NOT NULL,
    title         VARCHAR(500) NOT NULL DEFAULT '',
    content       TEXT        NOT NULL DEFAULT '',
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Index to quickly look up by OPC number (used for git log grep linkage)
CREATE INDEX IF NOT EXISTS ix_opc_number ON opc(number);
CREATE INDEX IF NOT EXISTS ix_opc_note_opc_id ON opc_note(opc_id);
CREATE INDEX IF NOT EXISTS ix_opc_artifact_opc_id ON opc_artifact(opc_id);

-- Manually pinned commits (in addition to auto-detected via git log grep)
CREATE TABLE IF NOT EXISTS opc_pinned_commit (
    opc_id     UUID          NOT NULL REFERENCES opc(id) ON DELETE CASCADE,
    hash       VARCHAR(40)   NOT NULL,
    short_hash VARCHAR(10)   NOT NULL DEFAULT '',
    subject    VARCHAR(1000) NOT NULL DEFAULT '',
    author     VARCHAR(200)  NOT NULL DEFAULT '',
    pinned_at  TIMESTAMPTZ   NOT NULL DEFAULT NOW(),
    pinned_by  VARCHAR(200)  NOT NULL DEFAULT '',
    PRIMARY KEY (opc_id, hash)
);
CREATE INDEX IF NOT EXISTS ix_opc_pinned_commit_opc_id ON opc_pinned_commit(opc_id);
CREATE INDEX IF NOT EXISTS ix_opc_artifact_type ON opc_artifact(opc_id, artifact_type);
