const AbstractManager = require("./AbstractManager");

class GameSaveManager extends AbstractManager {
  constructor() {
    super({ table: "game_saves" });
  }

  async getByUserId(userId) {
    const [rows] = await this.database.query(
      `SELECT * FROM ${this.table} WHERE user_id = ?`,
      [userId]
    );
    return rows[0] ?? null;
  }

  async upsert(userId, gameState, metadata) {
    const { lifetimeTadpoles, prestigeCount, playTimeSeconds } = metadata;
    const gameStateJson = JSON.stringify(gameState);

    const [result] = await this.database.query(
      `INSERT INTO ${this.table} (user_id, game_state, lifetime_tadpoles, prestige_count, play_time_seconds)
       VALUES (?, ?, ?, ?, ?)
       ON DUPLICATE KEY UPDATE
         game_state = VALUES(game_state),
         lifetime_tadpoles = VALUES(lifetime_tadpoles),
         prestige_count = VALUES(prestige_count),
         play_time_seconds = VALUES(play_time_seconds),
         last_save = CURRENT_TIMESTAMP`,
      [userId, gameStateJson, lifetimeTadpoles, prestigeCount, playTimeSeconds]
    );

    return result.affectedRows;
  }

  async delete(userId) {
    await this.database.query(
      `DELETE FROM ${this.table} WHERE user_id = ?`,
      [userId]
    );
  }
}

module.exports = GameSaveManager;
