-- Per-site log position tracking for the on-demand log review pipeline.
--
-- Without this, every scheduled review re-greps the same recent N lines of
-- each log source and surfaces the same errors over and over. Tracking last
-- offset/inode (for owned files) and last timestamp (for shared/streamed
-- sources like Apache error_log and docker logs) lets the next scan see only
-- novel content. When there is no new content the existing no-evidence
-- short-circuit in process-log-review.php skips the AI call entirely.
--
-- Idempotent (CREATE TABLE IF NOT EXISTS).

USE whp;

CREATE TABLE IF NOT EXISTS site_log_positions (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    site_id         INT NOT NULL,
    log_source      VARCHAR(255) NOT NULL,    -- e.g. file path, container name, or 'apache_error', 'dmesg'
    last_offset     BIGINT UNSIGNED DEFAULT 0,  -- file byte offset; 0 for non-file sources
    last_inode      BIGINT UNSIGNED DEFAULT 0,  -- detect rotation/truncation; 0 for non-file sources
    last_timestamp  BIGINT DEFAULT 0,           -- unix seconds; used by Apache/docker/shared sources
    updated_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_site_source (site_id, log_source),
    INDEX idx_site (site_id),
    CONSTRAINT fk_slp_site FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
