namespace ZB.MOM.WW.Secrets.Sqlite;

/// <summary>
/// Schema constants and table DDL for the secret SQLite store.
/// </summary>
public static class SqliteSecretsSchema
{
    /// <summary>
    /// The schema version this build creates and supports. This is the first version, so all DDL is a
    /// single-shot <c>CREATE ... IF NOT EXISTS</c>. The migrator refuses an on-disk version
    /// <em>newer</em> than this. Future additive columns (nullable <c>ALTER TABLE</c>s, gated by a
    /// <c>PRAGMA table_info</c> existence probe) would bump this and register a forward migration.
    /// </summary>
    public const int CurrentVersion = 1;

    /// <summary>Name of the single-row table tracking the applied schema version.</summary>
    public const string SchemaVersionTable = "schema_version";

    /// <summary>Name of the table storing envelope-encrypted secret records.</summary>
    public const string SecretTable = "secret";

    /// <summary>DDL creating the single-row schema-version table.</summary>
    public const string CreateSchemaVersionTable = """
        CREATE TABLE IF NOT EXISTS schema_version (
            id INTEGER PRIMARY KEY CHECK (id = 1),
            version INTEGER NOT NULL,
            applied_utc TEXT NOT NULL
        );
        """;

    /// <summary>DDL creating the envelope-encrypted secret record table.</summary>
    public const string CreateSecretTable = """
        CREATE TABLE IF NOT EXISTS secret (
            name          TEXT PRIMARY KEY,
            description   TEXT NULL,
            content_type  TEXT NOT NULL,
            ciphertext    BLOB NOT NULL,
            nonce         BLOB NOT NULL,
            tag           BLOB NOT NULL,
            wrapped_dek   BLOB NOT NULL,
            wrap_nonce    BLOB NOT NULL,
            wrap_tag      BLOB NOT NULL,
            kek_id        TEXT NOT NULL,
            revision      INTEGER NOT NULL DEFAULT 0,
            is_deleted    INTEGER NOT NULL DEFAULT 0,
            deleted_utc   TEXT NULL,
            created_utc   TEXT NOT NULL,
            updated_utc   TEXT NOT NULL,
            created_by    TEXT NULL,
            updated_by    TEXT NULL
        );
        """;

    /// <summary>DDL creating supporting indexes (idempotent).</summary>
    public const string CreateIndexes = """
        CREATE INDEX IF NOT EXISTS ix_secret_updated_utc
            ON secret (updated_utc);
        """;
}
