CREATE DATABASE IF NOT EXISTS hyapp_room
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE hyapp_room;

CREATE TABLE IF NOT EXISTS rooms (
  room_id VARCHAR(64) NOT NULL PRIMARY KEY,
  owner_user_id BIGINT NOT NULL,
  host_user_id BIGINT NOT NULL,
  seat_count INT NOT NULL,
  mode VARCHAR(64) NOT NULL,
  status VARCHAR(32) NOT NULL,
  created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS room_snapshots (
  room_id VARCHAR(64) NOT NULL PRIMARY KEY,
  room_version BIGINT NOT NULL,
  payload LONGBLOB NOT NULL,
  created_at TIMESTAMP(3) NOT NULL,
  updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  INDEX idx_room_snapshots_version (room_id, room_version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS room_command_log (
  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  room_id VARCHAR(64) NOT NULL,
  room_version BIGINT NOT NULL,
  command_id VARCHAR(128) NOT NULL,
  command_type VARCHAR(64) NOT NULL,
  payload LONGBLOB NOT NULL,
  replayable BOOLEAN NOT NULL,
  created_at TIMESTAMP(3) NOT NULL,
  UNIQUE KEY uk_room_command (room_id, command_id),
  KEY idx_room_command_replay (room_id, room_version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS room_outbox (
  event_id VARCHAR(128) NOT NULL PRIMARY KEY,
  event_type VARCHAR(64) NOT NULL,
  room_id VARCHAR(64) NOT NULL,
  status VARCHAR(32) NOT NULL,
  envelope LONGBLOB NOT NULL,
  created_at TIMESTAMP(3) NOT NULL,
  retry_count INT NOT NULL DEFAULT 0,
  last_error TEXT NULL,
  updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  KEY idx_room_outbox_pending (status, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

