-- Audit, özellik bayrakları, A/B iskeleti, robots.txt vb. çalışma zamanı yapılandırması.

CREATE TABLE IF NOT EXISTS audit_log (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  admin_user_id INT UNSIGNED NOT NULL,
  action VARCHAR(96) NOT NULL,
  entity_type VARCHAR(64) NOT NULL,
  entity_id VARCHAR(128) NOT NULL DEFAULT '',
  payload_json JSON NULL,
  ip_hash CHAR(64) NOT NULL DEFAULT '',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_audit_created (created_at),
  KEY idx_audit_entity (entity_type, entity_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS feature_flags (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  flag_key VARCHAR(96) NOT NULL,
  is_enabled TINYINT(1) NOT NULL DEFAULT 0,
  rollout_percent TINYINT UNSIGNED NOT NULL DEFAULT 0,
  description VARCHAR(255) NOT NULL DEFAULT '',
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_feature_flags_key (flag_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ab_experiments (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  experiment_key VARCHAR(96) NOT NULL,
  variants_json JSON NOT NULL,
  is_active TINYINT(1) NOT NULL DEFAULT 0,
  description VARCHAR(255) NOT NULL DEFAULT '',
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_ab_experiments_key (experiment_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS site_runtime_config (
  config_key VARCHAR(128) NOT NULL,
  config_value MEDIUMTEXT NOT NULL,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (config_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

SET @has_role := (
  SELECT COUNT(*) FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_users' AND COLUMN_NAME = 'role'
);
SET @sql_role := IF(@has_role = 0,
  'ALTER TABLE admin_users ADD COLUMN role VARCHAR(32) NOT NULL DEFAULT ''superadmin'' AFTER username',
  'SELECT 1');
PREPARE stmt FROM @sql_role; EXECUTE stmt; DEALLOCATE PREPARE stmt;

INSERT IGNORE INTO site_runtime_config (config_key, config_value) VALUES ('robots_txt', '');
INSERT IGNORE INTO site_runtime_config (config_key, config_value) VALUES ('robots_extra_disallow', '[]');
