-- Projects: agrupan apps, analysis y vaults bajo un tema comun.
-- Vaults: almacenes de datos (symlinks o directorios) asociados a proyectos o al registry.

CREATE TABLE IF NOT EXISTS projects (
    id               TEXT PRIMARY KEY,
    name             TEXT NOT NULL,
    description      TEXT NOT NULL DEFAULT '',
    tags             TEXT NOT NULL DEFAULT '[]',
    repo_url         TEXT NOT NULL DEFAULT '',
    dir_path         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 projects_fts USING fts5(
    id,
    name,
    description,
    tags,
    documentation,
    notes,
    content='projects',
    content_rowid='rowid'
);

CREATE TRIGGER IF NOT EXISTS projects_ai AFTER INSERT ON projects BEGIN
    INSERT INTO projects_fts(rowid, id, name, description, tags, documentation, notes)
    VALUES (new.rowid, new.id, new.name, new.description, new.tags, new.documentation, new.notes);
END;

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

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

-- Vaults: almacenes de datos trackados en el registry.
CREATE TABLE IF NOT EXISTS vaults (
    id               TEXT PRIMARY KEY,
    name             TEXT NOT NULL,
    project_id       TEXT NOT NULL DEFAULT '',
    description      TEXT NOT NULL DEFAULT '',
    path             TEXT NOT NULL DEFAULT '',
    symlink          INTEGER NOT NULL DEFAULT 0,
    tags             TEXT NOT NULL DEFAULT '[]',
    content_hash     TEXT NOT NULL DEFAULT '',
    created_at       TEXT NOT NULL,
    updated_at       TEXT NOT NULL
);

-- Columna project_id en apps y analysis para vincular a un proyecto.
ALTER TABLE apps ADD COLUMN project_id TEXT NOT NULL DEFAULT '';
ALTER TABLE analysis ADD COLUMN project_id TEXT NOT NULL DEFAULT '';
