-- MySQL schema for PLBA tracing.
-- Guarantees compatibility with TraceService levels: INFO, WARNING, ERROR.

CREATE TABLE IF NOT EXISTS trace_contexts (
    trace_id     VARCHAR(64) PRIMARY KEY,
    parent_id    VARCHAR(64) NULL,
    alias        VARCHAR(255) NOT NULL,
    type         VARCHAR(64) NULL,
    event_time   DATETIME(6) NOT NULL,
    attrs_json   JSON NOT NULL,
    KEY idx_trace_contexts_parent_id (parent_id),
    CONSTRAINT fk_trace_contexts_parent
        FOREIGN KEY (parent_id) REFERENCES trace_contexts(trace_id)
        ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS trace_messages (
    id           BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    trace_id     VARCHAR(64) NOT NULL,
    event_time   DATETIME(6) NOT NULL,
    step         VARCHAR(128) NOT NULL,
    status       VARCHAR(64) NOT NULL,
    level        ENUM('INFO', 'WARNING', 'ERROR') NOT NULL,
    message      TEXT NOT NULL,
    attrs_json   JSON NOT NULL,
    KEY idx_trace_messages_trace_id (trace_id),
    KEY idx_trace_messages_event_time (event_time),
    KEY idx_trace_messages_level (level),
    CONSTRAINT fk_trace_messages_context
        FOREIGN KEY (trace_id) REFERENCES trace_contexts(trace_id)
        ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Migration for existing installations.
-- If your `trace_messages.level` does not include WARNING, run this ALTER.
ALTER TABLE trace_messages
    MODIFY COLUMN level ENUM('INFO', 'WARNING', 'ERROR') NOT NULL;
