-- Migration 001: Ontology meta-schema (with inheritance, R3-1)
-- Defines entity types, relationship types, lifecycle definitions, and seed versioning.

CREATE TABLE lifecycle_defs (
    id            TEXT PRIMARY KEY,
    states        TEXT[] NOT NULL,
    default_state TEXT NOT NULL,
    terminal_states TEXT[] NOT NULL DEFAULT '{}',
    transitions   JSONB NOT NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE entity_types (
    name          TEXT PRIMARY KEY,
    parent_type   TEXT REFERENCES entity_types(name),
    is_abstract   BOOLEAN NOT NULL DEFAULT false,
    domain        TEXT NOT NULL,
    layer         TEXT NOT NULL CHECK (layer IN ('meta','infrastructure','governance','cognition')),
    description   TEXT,
    lifecycle_id  TEXT REFERENCES lifecycle_defs(id),
    attribute_schema JSONB,
    schema_version INTEGER NOT NULL DEFAULT 1,
    status        TEXT NOT NULL DEFAULT 'active',
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE relationship_types (
    name          TEXT PRIMARY KEY,
    inverse       TEXT,
    source_type   TEXT NOT NULL REFERENCES entity_types(name),
    target_type   TEXT NOT NULL REFERENCES entity_types(name),
    cardinality   TEXT NOT NULL CHECK (cardinality IN
                    ('one-to-one','one-to-many','many-to-one','many-to-many')),
    description   TEXT,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE seed_versions (
    file          TEXT PRIMARY KEY,
    content_hash  TEXT NOT NULL,
    applied_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);
