CREATE TABLE IF NOT EXISTS spells (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  class ENUM('wizard', 'priest', 'both') NOT NULL,
  tier TINYINT NOT NULL,
  casting_stat ENUM('INT', 'WIS') NOT NULL,
  duration VARCHAR(100) NOT NULL DEFAULT 'Instant',
  range VARCHAR(100) NOT NULL DEFAULT 'Near',
  is_focus TINYINT NOT NULL DEFAULT 0,
  description TEXT NOT NULL DEFAULT '',
  UNIQUE KEY uq_spells_name_class (name, class)
);

CREATE TABLE IF NOT EXISTS character_spells (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  character_id INT UNSIGNED NOT NULL,
  spell_id INT UNSIGNED NOT NULL,
  exhausted TINYINT NOT NULL DEFAULT 0,
  locked_until DATETIME DEFAULT NULL,
  focus_active TINYINT NOT NULL DEFAULT 0,
  focus_started_at DATETIME DEFAULT NULL,
  UNIQUE KEY uq_char_spell (character_id, spell_id),
  FOREIGN KEY (character_id) REFERENCES characters(id) ON DELETE CASCADE,
  FOREIGN KEY (spell_id) REFERENCES spells(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS character_conditions (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  character_id INT UNSIGNED NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT DEFAULT '',
  rounds_remaining INT DEFAULT NULL,
  expires_at DATETIME DEFAULT NULL,
  created_at DATETIME DEFAULT NOW(),
  FOREIGN KEY (character_id) REFERENCES characters(id) ON DELETE CASCADE
);

ALTER TABLE roll_log
  ADD COLUMN IF NOT EXISTS subtype VARCHAR(50) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS metadata TEXT DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS undone TINYINT NOT NULL DEFAULT 0
