# mcard/model/schema.py
"""
Shared SQL schema definitions for MCard storage engines.
"""

CARD_TABLE_SCHEMA = (
    """
    CREATE TABLE IF NOT EXISTS card (
        hash TEXT PRIMARY KEY,
        content TEXT NOT NULL,  -- Changed from BLOB to TEXT for human-readable storage
        g_time TEXT
    )
    """
)

HANDLE_REGISTRY_SCHEMA = (
    """
    CREATE TABLE IF NOT EXISTS handle_registry (
        handle TEXT PRIMARY KEY,       -- The user-defined handle (e.g., 'my_document')
        current_hash TEXT NOT NULL,    -- FK to the card.hash of the current version
        created_at TEXT NOT NULL,      -- ISO 8601 timestamp when handle was first created
        updated_at TEXT NOT NULL,      -- ISO 8601 timestamp when handle was last updated
        FOREIGN KEY (current_hash) REFERENCES card(hash)
    )
    """
)

HANDLE_HISTORY_SCHEMA = (
    """
    CREATE TABLE IF NOT EXISTS handle_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        handle TEXT NOT NULL,          -- The handle that was updated
        previous_hash TEXT NOT NULL,   -- The hash it pointed to before the update
        changed_at TEXT NOT NULL,      -- When the change occurred
        FOREIGN KEY (handle) REFERENCES handle_registry(handle),
        FOREIGN KEY (previous_hash) REFERENCES card(hash)
    )
    """
)

HANDLE_INDEX_SCHEMA = (
    """
    CREATE INDEX IF NOT EXISTS idx_handle_current_hash ON handle_registry(current_hash)
    """
)
