-- Proposals table: agent-generated improvement suggestions for the registry.
-- Lives in registry (not operations) because proposals benefit all projects.

CREATE TABLE IF NOT EXISTS proposals (
	id          TEXT PRIMARY KEY,
	kind        TEXT NOT NULL CHECK(kind IN ('new_function','new_type','improve_function','improve_type','new_pipeline')),
	target_id   TEXT NOT NULL DEFAULT '',
	title       TEXT NOT NULL,
	description TEXT NOT NULL DEFAULT '',
	evidence    TEXT NOT NULL DEFAULT '{}',
	status      TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','implemented')),
	created_by  TEXT NOT NULL DEFAULT '',
	reviewed_by TEXT NOT NULL DEFAULT '',
	created_at  TEXT NOT NULL,
	updated_at  TEXT NOT NULL
);

CREATE VIRTUAL TABLE IF NOT EXISTS proposals_fts USING fts5(
	id,
	title,
	description,
	evidence,
	content='proposals',
	content_rowid='rowid'
);

CREATE TRIGGER IF NOT EXISTS proposals_ai AFTER INSERT ON proposals BEGIN
	INSERT INTO proposals_fts(rowid, id, title, description, evidence)
	VALUES (new.rowid, new.id, new.title, new.description, new.evidence);
END;

CREATE TRIGGER IF NOT EXISTS proposals_ad AFTER DELETE ON proposals BEGIN
	INSERT INTO proposals_fts(proposals_fts, rowid, id, title, description, evidence)
	VALUES ('delete', old.rowid, old.id, old.title, old.description, old.evidence);
END;

CREATE TRIGGER IF NOT EXISTS proposals_au AFTER UPDATE ON proposals BEGIN
	INSERT INTO proposals_fts(proposals_fts, rowid, id, title, description, evidence)
	VALUES ('delete', old.rowid, old.id, old.title, old.description, old.evidence);
	INSERT INTO proposals_fts(rowid, id, title, description, evidence)
	VALUES (new.rowid, new.id, new.title, new.description, new.evidence);
END;
