-- Executions, assertions, and assertion_results tables.
-- Closes the autonomous improvement loop: execute -> assert -> analyze.

CREATE TABLE IF NOT EXISTS executions (
	id          TEXT PRIMARY KEY,
	pipeline_id TEXT NOT NULL,
	relation_id TEXT NOT NULL DEFAULT '',
	status      TEXT NOT NULL CHECK(status IN ('success','failure','partial')),
	started_at  TEXT NOT NULL,
	ended_at    TEXT,
	duration_ms INTEGER,
	records_in  INTEGER,
	records_out INTEGER,
	error       TEXT NOT NULL DEFAULT '',
	metrics     TEXT NOT NULL DEFAULT '{}',
	created_at  TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS assertions (
	id          TEXT PRIMARY KEY,
	entity_id   TEXT NOT NULL REFERENCES entities(id),
	name        TEXT NOT NULL,
	kind        TEXT NOT NULL,
	rule        TEXT NOT NULL,
	severity    TEXT NOT NULL DEFAULT 'warning' CHECK(severity IN ('critical','warning','info')),
	description TEXT NOT NULL DEFAULT '',
	active      INTEGER NOT NULL DEFAULT 1,
	created_at  TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS assertion_results (
	id           TEXT PRIMARY KEY,
	assertion_id TEXT NOT NULL REFERENCES assertions(id),
	execution_id TEXT NOT NULL DEFAULT '',
	status       TEXT NOT NULL CHECK(status IN ('pass','fail','skip')),
	value        TEXT NOT NULL DEFAULT '{}',
	message      TEXT NOT NULL DEFAULT '',
	evaluated_at TEXT NOT NULL
);

CREATE VIRTUAL TABLE IF NOT EXISTS assertions_fts USING fts5(
	id,
	name,
	description,
	rule,
	content='assertions',
	content_rowid='rowid'
);

CREATE TRIGGER IF NOT EXISTS assertions_ai AFTER INSERT ON assertions BEGIN
	INSERT INTO assertions_fts(rowid, id, name, description, rule)
	VALUES (new.rowid, new.id, new.name, new.description, new.rule);
END;

CREATE TRIGGER IF NOT EXISTS assertions_ad AFTER DELETE ON assertions BEGIN
	INSERT INTO assertions_fts(assertions_fts, rowid, id, name, description, rule)
	VALUES ('delete', old.rowid, old.id, old.name, old.description, old.rule);
END;

CREATE TRIGGER IF NOT EXISTS assertions_au AFTER UPDATE ON assertions BEGIN
	INSERT INTO assertions_fts(assertions_fts, rowid, id, name, description, rule)
	VALUES ('delete', old.rowid, old.id, old.name, old.description, old.rule);
	INSERT INTO assertions_fts(rowid, id, name, description, rule)
	VALUES (new.rowid, new.id, new.name, new.description, new.rule);
END;
