-- DBN DMS migration 003 — saved searches / smart folders

CREATE TABLE IF NOT EXISTS client_saved_searches (
  id         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  client_id  INT UNSIGNED NOT NULL,
  user_id    INT UNSIGNED NOT NULL,
  name       VARCHAR(120) NOT NULL,
  icon       VARCHAR(40) NULL,
  color      VARCHAR(7) NULL,
  query_json JSON NOT NULL COMMENT '{q, category, tags[], folder_id, source_type, status, include_subfolders}',
  is_shared  TINYINT(1) NOT NULL DEFAULT 0,
  sort_order SMALLINT NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_client_user (client_id, user_id),
  KEY idx_shared      (client_id, is_shared),
  CONSTRAINT fk_css_client FOREIGN KEY (client_id) REFERENCES clients(id)      ON DELETE CASCADE,
  CONSTRAINT fk_css_user   FOREIGN KEY (user_id)   REFERENCES client_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  COMMENT='Persisted filter sets ("smart folders"). is_shared=1 = visible to whole tenant.';
