CREATE TABLE IF NOT EXISTS rh_schema_migrations (
  version VARCHAR(64) CHARACTER SET ascii NOT NULL,
  checksum CHAR(64) CHARACTER SET ascii NOT NULL,
  applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_roles (
  user_id INT(10) UNSIGNED NOT NULL,
  role ENUM('owner','admin','member') NOT NULL DEFAULT 'member',
  granted_by INT(10) UNSIGNED DEFAULT NULL,
  granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (user_id),
  KEY granted_by (granted_by),
  CONSTRAINT rh_roles_user_fk FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE,
  CONSTRAINT rh_roles_granter_fk FOREIGN KEY (granted_by) REFERENCES users(user_id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_modules (
  module_slug VARCHAR(64) CHARACTER SET ascii NOT NULL,
  display_name VARCHAR(80) NOT NULL,
  state ENUM('enabled','disabled','maintenance') NOT NULL DEFAULT 'disabled',
  utility_module TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
  sort_order SMALLINT UNSIGNED NOT NULL DEFAULT 0,
  updated_by INT(10) UNSIGNED DEFAULT NULL,
  reason VARCHAR(500) NOT NULL DEFAULT '',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (module_slug),
  KEY state_sort (state, sort_order),
  CONSTRAINT rh_modules_updater_fk FOREIGN KEY (updated_by) REFERENCES users(user_id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_module_audit (
  audit_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  module_slug VARCHAR(64) CHARACTER SET ascii NOT NULL,
  old_state ENUM('enabled','disabled','maintenance') DEFAULT NULL,
  new_state ENUM('enabled','disabled','maintenance') NOT NULL,
  actor_id INT(10) UNSIGNED NOT NULL,
  reason VARCHAR(500) NOT NULL DEFAULT '',
  changed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (audit_id),
  KEY module_time (module_slug, changed_at),
  KEY actor_time (actor_id, changed_at),
  CONSTRAINT rh_module_audit_module_fk FOREIGN KEY (module_slug) REFERENCES rh_modules(module_slug) ON DELETE CASCADE,
  CONSTRAINT rh_module_audit_actor_fk FOREIGN KEY (actor_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_items (
  item_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  owner_id INT(10) UNSIGNED NOT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  item_type ENUM('task','list','goal','event','note','recipe','custom') NOT NULL DEFAULT 'task',
  source_type VARCHAR(32) CHARACTER SET ascii NOT NULL DEFAULT '',
  source_id BIGINT UNSIGNED DEFAULT NULL,
  parent_item_id BIGINT UNSIGNED DEFAULT NULL,
  title VARCHAR(160) NOT NULL,
  body TEXT NOT NULL,
  due_date DATE DEFAULT NULL,
  scheduled_at DATETIME DEFAULT NULL,
  duration_minutes SMALLINT UNSIGNED DEFAULT NULL,
  all_day TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
  time_block ENUM('','morning','afternoon','evening','night') NOT NULL DEFAULT '',
  emoji VARCHAR(32) NOT NULL DEFAULT '',
  color_tag VARCHAR(32) CHARACTER SET ascii NOT NULL DEFAULT '',
  roots_json TEXT NOT NULL,
  visibility ENUM('private','followers','public') NOT NULL DEFAULT 'private',
  public_description TEXT NOT NULL,
  status ENUM('open','completed','archived') NOT NULL DEFAULT 'open',
  completed_at DATETIME DEFAULT NULL,
  metadata_json LONGTEXT NOT NULL,
  version INT UNSIGNED NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  deleted_at DATETIME DEFAULT NULL,
  PRIMARY KEY (item_id),
  UNIQUE KEY owner_mutation (owner_id, mutation_id),
  KEY owner_agenda (owner_id, due_date, status, item_id),
  KEY owner_schedule (owner_id, scheduled_at, item_id),
  KEY public_agenda (visibility, due_date, status),
  KEY parent_item (parent_item_id),
  CONSTRAINT rh_items_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE,
  CONSTRAINT rh_items_parent_fk FOREIGN KEY (parent_item_id) REFERENCES rh_items(item_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_subtasks (
  subtask_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  item_id BIGINT UNSIGNED NOT NULL,
  owner_id INT(10) UNSIGNED NOT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  title VARCHAR(160) NOT NULL,
  notes VARCHAR(500) NOT NULL DEFAULT '',
  quantity VARCHAR(40) NOT NULL DEFAULT '',
  position INT UNSIGNED NOT NULL DEFAULT 0,
  completed_at DATETIME DEFAULT NULL,
  version INT UNSIGNED NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  deleted_at DATETIME DEFAULT NULL,
  PRIMARY KEY (subtask_id),
  UNIQUE KEY owner_mutation (owner_id, mutation_id),
  KEY item_position (item_id, position, subtask_id),
  CONSTRAINT rh_subtasks_item_fk FOREIGN KEY (item_id) REFERENCES rh_items(item_id) ON DELETE CASCADE,
  CONSTRAINT rh_subtasks_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_habits (
  habit_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  owner_id INT(10) UNSIGNED NOT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  title VARCHAR(160) NOT NULL,
  notes VARCHAR(500) NOT NULL DEFAULT '',
  color_tag VARCHAR(32) CHARACTER SET ascii NOT NULL DEFAULT '',
  archived_at DATETIME DEFAULT NULL,
  version INT UNSIGNED NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (habit_id),
  UNIQUE KEY owner_mutation (owner_id, mutation_id),
  KEY owner_active (owner_id, archived_at, habit_id),
  CONSTRAINT rh_habits_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_habit_completions (
  habit_id BIGINT UNSIGNED NOT NULL,
  owner_id INT(10) UNSIGNED NOT NULL,
  completion_date DATE NOT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  completed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (habit_id, completion_date),
  UNIQUE KEY owner_mutation (owner_id, mutation_id),
  KEY owner_date (owner_id, completion_date),
  CONSTRAINT rh_habit_completions_habit_fk FOREIGN KEY (habit_id) REFERENCES rh_habits(habit_id) ON DELETE CASCADE,
  CONSTRAINT rh_habit_completions_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_notebooks (
  owner_id INT(10) UNSIGNED NOT NULL,
  document MEDIUMTEXT NOT NULL,
  revision INT UNSIGNED NOT NULL DEFAULT 1,
  last_mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (owner_id),
  UNIQUE KEY owner_mutation (owner_id, last_mutation_id),
  CONSTRAINT rh_notebooks_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_reminders (
  reminder_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  owner_id INT(10) UNSIGNED NOT NULL,
  item_id BIGINT UNSIGNED DEFAULT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  remind_at DATETIME NOT NULL,
  delivery_type ENUM('local','in_app','email','push') NOT NULL DEFAULT 'local',
  status ENUM('scheduled','sent','cancelled','failed') NOT NULL DEFAULT 'scheduled',
  payload_json TEXT NOT NULL,
  sent_at DATETIME DEFAULT NULL,
  cancelled_at DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (reminder_id),
  UNIQUE KEY owner_mutation (owner_id, mutation_id),
  KEY due_delivery (status, remind_at),
  KEY owner_item (owner_id, item_id),
  CONSTRAINT rh_reminders_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE,
  CONSTRAINT rh_reminders_item_fk FOREIGN KEY (item_id) REFERENCES rh_items(item_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_preferences (
  owner_id INT(10) UNSIGNED NOT NULL,
  preference_key VARCHAR(80) CHARACTER SET ascii NOT NULL,
  value_json LONGTEXT NOT NULL,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (owner_id, preference_key),
  CONSTRAINT rh_preferences_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_mutation_receipts (
  owner_id INT(10) UNSIGNED NOT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  entity_type VARCHAR(40) CHARACTER SET ascii NOT NULL,
  entity_id BIGINT UNSIGNED DEFAULT NULL,
  response_json LONGTEXT NOT NULL,
  processed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (owner_id, mutation_id),
  KEY processed_at (processed_at),
  CONSTRAINT rh_mutation_receipts_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rh_conflicts (
  conflict_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  owner_id INT(10) UNSIGNED NOT NULL,
  mutation_id CHAR(36) CHARACTER SET ascii NOT NULL,
  entity_type VARCHAR(40) CHARACTER SET ascii NOT NULL,
  entity_id BIGINT UNSIGNED DEFAULT NULL,
  client_version INT UNSIGNED DEFAULT NULL,
  server_version INT UNSIGNED DEFAULT NULL,
  client_payload_json LONGTEXT NOT NULL,
  server_payload_json LONGTEXT NOT NULL,
  resolution ENUM('pending','keep_server','keep_client','save_as_new') NOT NULL DEFAULT 'pending',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  resolved_at DATETIME DEFAULT NULL,
  PRIMARY KEY (conflict_id),
  UNIQUE KEY owner_mutation (owner_id, mutation_id),
  KEY owner_pending (owner_id, resolution, created_at),
  CONSTRAINT rh_conflicts_owner_fk FOREIGN KEY (owner_id) REFERENCES users(user_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO rh_modules (module_slug, display_name, state, utility_module, sort_order) VALUES
  ('today', 'Today', 'enabled', 1, 10),
  ('calendar', 'Calendar', 'enabled', 1, 20),
  ('planning', 'Planning', 'enabled', 1, 30),
  ('notebook', 'Notebook', 'enabled', 1, 40),
  ('habits', 'Habits', 'enabled', 1, 50),
  ('focus', 'Focus', 'disabled', 1, 60),
  ('notifications', 'Notifications', 'enabled', 1, 70),
  ('social_feed', 'Community Feed', 'disabled', 0, 100),
  ('messaging', 'Messaging', 'disabled', 0, 110),
  ('courses', 'Courses', 'disabled', 0, 120),
  ('botanica', 'Botanica', 'disabled', 0, 130),
  ('publishing', 'Publishing', 'disabled', 0, 140),
  ('payments', 'Payments', 'disabled', 0, 150)
ON DUPLICATE KEY UPDATE display_name = VALUES(display_name), utility_module = VALUES(utility_module), sort_order = VALUES(sort_order);
