-- Runtime MySQL schema for Telegram validator bot (new contour)
-- Compatible with RUNTIME_DB_TABLE_* defaults from MAIN/config.php

CREATE TABLE IF NOT EXISTS runtime_objects (
    object_code      VARCHAR(64)  NOT NULL,
    subdomain        VARCHAR(128) NOT NULL,
    name             VARCHAR(255) NOT NULL,
    name_en          VARCHAR(255) NULL,
    name_ru          VARCHAR(255) NULL,
    name_lv          VARCHAR(255) NULL,
    telegram_token   VARCHAR(255) NULL,
    token            VARCHAR(255) NULL,
    status           VARCHAR(32)  NOT NULL DEFAULT 'active',
    created_at       TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at       TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (object_code),
    UNIQUE KEY uq_runtime_objects_subdomain (subdomain)
);

CREATE TABLE IF NOT EXISTS runtime_object_configs (
    object_code      VARCHAR(64) NOT NULL,
    api_keys_json    LONGTEXT    NULL,
    api_server_json  LONGTEXT    NULL,
    discounts_json   LONGTEXT    NULL,
    subdomain        VARCHAR(128) NULL,
    created_at       TIMESTAMP   NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at       TIMESTAMP   NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (object_code),
    CONSTRAINT fk_runtime_object_configs_object
        FOREIGN KEY (object_code) REFERENCES runtime_objects(object_code)
        ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS runtime_chat_object_mapping (
    chat_id          VARCHAR(64) NOT NULL,
    object_code      VARCHAR(64) NOT NULL,
    updated_at       TIMESTAMP   NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (chat_id, object_code),
    KEY idx_runtime_mapping_chat_updated (chat_id, updated_at)
);

CREATE TABLE IF NOT EXISTS runtime_user_sessions (
    chat_id          VARCHAR(64) NOT NULL,
    object_code      VARCHAR(64) NOT NULL,
    session_json     LONGTEXT    NOT NULL,
    updated_at       TIMESTAMP   NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (chat_id, object_code),
    KEY idx_runtime_sessions_chat_updated (chat_id, updated_at)
);
