-- Clavitor Vault Schema (Simplified - Single Node)
-- WL3s stored locally, no POP distribution yet

-- WebAuthn Credentials (P0 → WL3 mappings)
-- Each device that can unlock this vault has an entry here
CREATE TABLE credentials (
    credential_id   BLOB PRIMARY KEY,     -- WebAuthn credential ID (raw bytes)
    p0              TEXT NOT NULL,        -- First 4 bytes of PRF (hex, lookup key)
    wrapped_l3      BLOB NOT NULL,        -- The L3 encrypted with PRF
    device_name     TEXT,                 -- "YubiKey 5", "iPhone Touch ID"
    device_type     TEXT,                 -- "cross-platform", "platform", "hybrid"
    created_at      INTEGER NOT NULL,
    last_used_at    INTEGER
);

CREATE INDEX idx_credentials_p0 ON credentials(p0);

-- Agents (CLI, CI/CD, extensions) - unchanged
CREATE TABLE agents (
    id              INTEGER PRIMARY KEY,
    name            TEXT NOT NULL,
    token_hash      TEXT UNIQUE NOT NULL, -- SHA256 of agent token
    scopes          TEXT DEFAULT '',       -- Comma-separated scope IDs
    all_access      INTEGER DEFAULT 0,     -- 1 = reads everything
    created_at      INTEGER NOT NULL,
    last_used_at    INTEGER,
    status          TEXT DEFAULT 'active'  -- active, revoked
);

-- Vault Entries (passwords, notes, etc.) - unchanged
CREATE TABLE entries (
    id              INTEGER PRIMARY KEY,
    type            TEXT NOT NULL,         -- LOGIN, CARD, NOTE, etc.
    scopes          TEXT DEFAULT '',       -- Which agents can access
    title           BLOB,                  -- L1 encrypted
    username        BLOB,                  -- L2 encrypted
    password        BLOB,                  -- L2 encrypted  
    url             BLOB,                  -- L2 encrypted
    notes           BLOB,                  -- L3 encrypted (hardware-only)
    custom_fields   BLOB,                  -- L2/L3 encrypted JSON
    created_at      INTEGER NOT NULL,
    updated_at      INTEGER
);

-- TOTP seeds for 2FA codes
CREATE TABLE totp_seeds (
    id              INTEGER PRIMARY KEY,
    entry_id        INTEGER REFERENCES entries(id),
    seed            BLOB NOT NULL,         -- L2 encrypted TOTP secret
    algorithm       TEXT DEFAULT 'SHA1',
    digits          INTEGER DEFAULT 6,
    period          INTEGER DEFAULT 30
);

-- Audit log
CREATE TABLE audit_log (
    id              INTEGER PRIMARY KEY,
    occurred_at     INTEGER NOT NULL,
    action          TEXT NOT NULL,         -- unlock, agent_access, entry_read, etc.
    actor_type      TEXT,                  -- human, agent
    actor_id        TEXT,                  -- credential_id or agent_id
    entry_id        INTEGER,               -- If applicable
    details         TEXT                   -- JSON
);

CREATE INDEX idx_audit_time ON audit_log(occurred_at);
