-- Add migration script here

CREATE TABLE kv2_engine_cfg (
    engine_path TEXT PRIMARY KEY REFERENCES secret_engines (mount_point),
    max_versions UNSIGNED INTEGER CHECK ( max_versions > 0 ), -- Shall be proper NULL if 0
    max_age_secs UNSIGNED INTEGER CHECK ( max_versions > 0 ), -- Shall be proper NULL if 0
    cas_required BOOLEAN NOT NULL DEFAULT (FALSE)
);

CREATE TABLE kv2_metadata (
    engine_path TEXT NOT NULL REFERENCES secret_engines (mount_point),
    secret_path TEXT NOT NULL,

    cas_required INTEGER NOT NULL, -- no bool datatype in sqlite
    created_time TIMESTAMP NOT NULL,
    delete_version_after TEXT, -- May be NULL
    max_versions INTEGER NOT NULL,
    updated_time TIMESTAMP NOT NULL,
    custom_data TEXT,

    PRIMARY KEY (engine_path, secret_path)
);

CREATE TABLE kv2_secret_version (
    engine_path TEXT NOT NULL,
    secret_path TEXT NOT NULL,

    version_number INTEGER NOT NULL CHECK ( version_number > 0 ),
    created_time DATETIME NOT NULL,
    deletion_time DATETIME,

    encrypted_data BLOB NOT NULL,
    nonce BLOB NOT NULL CHECK ( length(nonce) = 12 ),

    PRIMARY KEY (engine_path, secret_path, version_number),
    FOREIGN KEY (engine_path, secret_path) REFERENCES kv2_metadata(engine_path, secret_path)
);
