-- AI Monitor ignore rules: per-finding suppression with global/user/site scope.
-- Match fields combine with AND-semantics: if a rule sets multiple match_*
-- columns, ALL of them must match the finding for the rule to apply.
-- Idempotent — uses IF NOT EXISTS; safe to re-run.

USE whp;

CREATE TABLE IF NOT EXISTS ai_monitor_ignore_rules (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    scope ENUM('global','user','site') NOT NULL,
    username VARCHAR(32) NULL,
    site_id INT NULL,
    match_category VARCHAR(50) NULL,
    match_severity VARCHAR(20) NULL,
    match_title_substr VARCHAR(255) NULL,
    match_raw_regex VARCHAR(500) NULL,
    reason TEXT NOT NULL,
    enabled TINYINT(1) NOT NULL DEFAULT 1,
    created_by VARCHAR(32) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    hit_count INT UNSIGNED NOT NULL DEFAULT 0,
    last_hit_at DATETIME NULL,
    INDEX idx_scope_enabled (scope, enabled),
    INDEX idx_site (site_id),
    INDEX idx_user (username),
    CONSTRAINT fk_aimr_site FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  COMMENT='AI Monitor ignore rules. match_* columns are AND-combined: every non-null match_* must match the finding for the rule to apply.';

CREATE TABLE IF NOT EXISTS ai_monitor_ignore_hits (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    rule_id INT UNSIGNED NOT NULL,
    site_id INT NULL,
    username VARCHAR(32) NULL,
    matched_category VARCHAR(50) NULL,
    matched_title VARCHAR(255) NULL,
    matched_signature VARCHAR(64) NULL,
    hit_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_rule_time (rule_id, hit_at),
    INDEX idx_user (username),
    CONSTRAINT fk_aimh_rule FOREIGN KEY (rule_id) REFERENCES ai_monitor_ignore_rules(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  COMMENT='Per-hit audit trail for ai_monitor_ignore_rules. Drives the recent-hits drill-down in the admin UI.';
