-- =============================================================================
-- Module 6.6: Platform Stabilization / Part 2
-- Migration 010 — preview_sessions
-- =============================================================================

CREATE TABLE IF NOT EXISTS `preview_sessions` (
    `id`               BIGINT UNSIGNED  NOT NULL AUTO_INCREMENT,
    `user_id`          BIGINT UNSIGNED  NOT NULL,
    `website_id`       BIGINT UNSIGNED  NULL       DEFAULT NULL COMMENT 'FK → websites.id',
    `template_id`      BIGINT UNSIGNED  NULL       DEFAULT NULL COMMENT 'FK → templates.id',

    -- Viewport & display
    `device`           ENUM('desktop','tablet','mobile') NOT NULL DEFAULT 'desktop',
    `zoom`             TINYINT UNSIGNED NOT NULL DEFAULT 100     COMMENT 'Zoom percent: 25–200',

    -- Navigation state
    `current_page`     VARCHAR(255)     NOT NULL DEFAULT '/'     COMMENT 'Active page slug',
    `scroll_x`         SMALLINT         NOT NULL DEFAULT 0,
    `scroll_y`         SMALLINT         NOT NULL DEFAULT 0,

    -- Renderer state
    `last_snapshot`    JSON             NULL       DEFAULT NULL  COMMENT 'Last rendered snapshot {sections,colors,fonts,content,images}',
    `history`          JSON             NOT NULL                 COMMENT 'Array of recently visited page slugs (max 10)',

    `created_at`       DATETIME         NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at`       DATETIME         NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    PRIMARY KEY (`id`),
    UNIQUE  KEY `uq_preview_sessions_user_website` (`user_id`, `website_id`),
    INDEX         `idx_preview_sessions_user`       (`user_id`),
    INDEX         `idx_preview_sessions_website`    (`website_id`),
    INDEX         `idx_preview_sessions_template`   (`template_id`),
    INDEX         `idx_preview_sessions_updated`    (`updated_at`),

    CONSTRAINT `fk_preview_sessions_website`
        FOREIGN KEY (`website_id`)
        REFERENCES  `websites` (`id`)
        ON DELETE CASCADE
        ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
