-- Modules: reusable cohesive units (e.g. data_table) versioned with semver.
-- A module groups a set of related registry functions/types under a single
-- versioned artefact that apps opt into via uses_modules in app.md.
--
-- Modules son datos vivos: fn sync los replica entre PCs igual que apps/proposals.
-- Aunque la fuente es modules/*/module.md (parseable), conservamos created_at /
-- updated_at de forma persistente para mantener historico cross-PC.

CREATE TABLE IF NOT EXISTS modules (
    id               TEXT PRIMARY KEY,
    name             TEXT NOT NULL,
    version          TEXT NOT NULL DEFAULT '0.0.0',
    lang             TEXT NOT NULL,
    description      TEXT NOT NULL DEFAULT '',
    members          TEXT NOT NULL DEFAULT '[]',
    tags             TEXT NOT NULL DEFAULT '[]',
    dir_path         TEXT NOT NULL DEFAULT '',
    repo_url         TEXT NOT NULL DEFAULT '',
    documentation    TEXT NOT NULL DEFAULT '',
    notes            TEXT NOT NULL DEFAULT '',
    content_hash     TEXT NOT NULL DEFAULT '',
    created_at       TEXT NOT NULL,
    updated_at       TEXT NOT NULL
);

CREATE VIRTUAL TABLE IF NOT EXISTS modules_fts USING fts5(
    id,
    name,
    description,
    tags,
    members,
    documentation,
    notes,
    content='modules',
    content_rowid='rowid'
);

CREATE TRIGGER IF NOT EXISTS modules_ai AFTER INSERT ON modules BEGIN
    INSERT INTO modules_fts(rowid, id, name, description, tags, members, documentation, notes)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.members, new.documentation, new.notes);
END;

CREATE TRIGGER IF NOT EXISTS modules_ad AFTER DELETE ON modules BEGIN
    INSERT INTO modules_fts(modules_fts, rowid, id, name, description, tags, members, documentation, notes)
    VALUES ('delete', old.rowid, old.id, old.name, old.description, old.tags, old.members, old.documentation, old.notes);
END;

CREATE TRIGGER IF NOT EXISTS modules_au AFTER UPDATE ON modules BEGIN
    INSERT INTO modules_fts(modules_fts, rowid, id, name, description, tags, members, documentation, notes)
    VALUES ('delete', old.rowid, old.id, old.name, old.description, old.tags, old.members, old.documentation, old.notes);
    INSERT INTO modules_fts(rowid, id, name, description, tags, members, documentation, notes)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.members, new.documentation, new.notes);
END;

-- uses_modules en apps/analysis: lista declarativa de modulos consumidos.
ALTER TABLE apps ADD COLUMN uses_modules TEXT NOT NULL DEFAULT '[]';
ALTER TABLE analysis ADD COLUMN uses_modules TEXT NOT NULL DEFAULT '[]';
