-- IHF Phase 3: Governance and Decision Linkage
-- Adds: requirements, decision_records, policy_references,
--       implementation_change_references
-- Extends: requirement_candidates (adds requirement_id back-reference)

CREATE TABLE requirements (
    id UUID DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,
    title TEXT NOT NULL,
    description TEXT NOT NULL,
    source_candidate_id UUID NOT NULL REFERENCES requirement_candidates(id) ON DELETE RESTRICT,
    status TEXT NOT NULL DEFAULT 'active',
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL
);

CREATE INDEX requirements_source_candidate_id_idx ON requirements (source_candidate_id);

CREATE TABLE decision_records (
    id UUID DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,
    title TEXT NOT NULL,
    rationale TEXT NOT NULL,
    outcome TEXT NOT NULL,
    requirement_id UUID REFERENCES requirements(id) ON DELETE SET NULL,
    candidate_id UUID REFERENCES requirement_candidates(id) ON DELETE SET NULL,
    decided_by UUID REFERENCES users(id),
    decided_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL
);

CREATE INDEX decision_records_outcome_idx ON decision_records (outcome);
CREATE INDEX decision_records_requirement_id_idx ON decision_records (requirement_id);

CREATE TABLE policy_references (
    id UUID DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,
    decision_id UUID NOT NULL REFERENCES decision_records(id) ON DELETE CASCADE,
    policy_scope TEXT NOT NULL,
    constraint_note TEXT,
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL
);

CREATE INDEX policy_references_decision_id_idx ON policy_references (decision_id);

CREATE TABLE implementation_change_references (
    id UUID DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,
    decision_id UUID NOT NULL REFERENCES decision_records(id) ON DELETE CASCADE,
    work_item_ref TEXT NOT NULL,
    system TEXT NOT NULL DEFAULT 'github',
    linked_by UUID REFERENCES users(id),
    linked_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL
);

CREATE INDEX impl_change_refs_decision_id_idx ON implementation_change_references (decision_id);

ALTER TABLE requirement_candidates
    ADD COLUMN requirement_id UUID REFERENCES requirements(id) ON DELETE SET NULL;
