-- Apps table: applications that consume functions/types from the registry.

CREATE TABLE IF NOT EXISTS apps (
    id               TEXT PRIMARY KEY,
    name             TEXT NOT NULL,
    lang             TEXT NOT NULL,
    domain           TEXT NOT NULL,
    description      TEXT NOT NULL,
    tags             TEXT NOT NULL DEFAULT '[]',
    uses_functions   TEXT NOT NULL DEFAULT '[]',
    uses_types       TEXT NOT NULL DEFAULT '[]',
    framework        TEXT NOT NULL DEFAULT '',
    entry_point      TEXT NOT NULL DEFAULT '',
    documentation    TEXT NOT NULL DEFAULT '',
    notes            TEXT NOT NULL DEFAULT '',
    dir_path         TEXT NOT NULL DEFAULT '',
    created_at       TEXT NOT NULL,
    updated_at       TEXT NOT NULL
);

CREATE VIRTUAL TABLE IF NOT EXISTS apps_fts USING fts5(
    id,
    name,
    description,
    tags,
    domain,
    documentation,
    notes,
    content='apps',
    content_rowid='rowid'
);

CREATE TRIGGER IF NOT EXISTS apps_ai AFTER INSERT ON apps BEGIN
    INSERT INTO apps_fts(rowid, id, name, description, tags, domain, documentation, notes)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.domain, new.documentation, new.notes);
END;

CREATE TRIGGER IF NOT EXISTS apps_ad AFTER DELETE ON apps BEGIN
    INSERT INTO apps_fts(apps_fts, rowid, id, name, description, tags, domain, documentation, notes)
    VALUES ('delete', old.rowid, old.id, old.name, old.description, old.tags, old.domain, old.documentation, old.notes);
END;

CREATE TRIGGER IF NOT EXISTS apps_au AFTER UPDATE ON apps BEGIN
    INSERT INTO apps_fts(apps_fts, rowid, id, name, description, tags, domain, documentation, notes)
    VALUES ('delete', old.rowid, old.id, old.name, old.description, old.tags, old.domain, old.documentation, old.notes);
    INSERT INTO apps_fts(rowid, id, name, description, tags, domain, documentation, notes)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.domain, new.documentation, new.notes);
END;
