USE aihub;

CREATE TABLE IF NOT EXISTS crash_rounds (
  id INT AUTO_INCREMENT PRIMARY KEY,
  crash_point DECIMAL(10,2) NOT NULL DEFAULT 1.00,
  phase ENUM('betting','flying','crashed') NOT NULL DEFAULT 'betting',
  betting_ends_at DATETIME NOT NULL,
  flying_started_at DATETIME NULL,
  crashed_at DATETIME NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_phase (phase)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS crash_bets (
  id INT AUTO_INCREMENT PRIMARY KEY,
  round_id INT NOT NULL,
  user_id INT NOT NULL,
  slot TINYINT NOT NULL DEFAULT 1,
  stake DECIMAL(15,2) NOT NULL,
  cashout_multiplier DECIMAL(10,2) NULL,
  payout DECIMAL(15,2) NOT NULL DEFAULT 0,
  status ENUM('active','cashed_out','lost','cancelled') NOT NULL DEFAULT 'active',
  auto_cashout_target DECIMAL(10,2) NULL,
  auto_bet TINYINT(1) NOT NULL DEFAULT 0,
  is_bot TINYINT(1) NOT NULL DEFAULT 0,
  bot_name VARCHAR(40) NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (round_id) REFERENCES crash_rounds(id) ON DELETE CASCADE,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  INDEX idx_round (round_id),
  INDEX idx_user_round (user_id, round_id)
) ENGINE=InnoDB;

INSERT INTO settings (setting_key, setting_value) VALUES
('crash_betting_seconds', '5'),
('crash_crashed_pause_seconds', '2'),
('crash_house_edge_pct', '3'),
('crash_max_multiplier', '100'),
('crash_growth_rate', '0.000083')
ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value);
