import gleam/dynamic/decode
import gleam/json
import gleam/option

pub type Player {
  Player(name: String, id: Int, score: Int, buzz_in_time: option.Option(Float))
}

pub fn serialize(player: Player) -> json.Json {
  json.object([
    #("name", json.string(player.name)),
    #("id", json.int(player.id)),
    #("score", json.int(player.score)),
    #("buzz_in_time", json.nullable(player.buzz_in_time, json.float)),
  ])
}

pub fn decoder() -> decode.Decoder(Player) {
  use name <- decode.field("name", decode.string)
  use id <- decode.field("id", decode.int)
  use score <- decode.field("score", decode.int)
  use buzz_in_time <- decode.field(
    "buzz_in_time",
    decode.optional(decode.float),
  )
  decode.success(Player(name:, id:, score:, buzz_in_time:))
}
