package de.nowchess.backcore.resource

import io.quarkus.test.junit.QuarkusTest
import io.restassured.RestAssured
import org.hamcrest.Matchers.{equalTo, matchesPattern, notNullValue}
import org.junit.jupiter.api.Test

@QuarkusTest
class GameResourceTest:

  @Test
  def createGameReturns201WithGameId(): Unit =
    RestAssured
      .`given`()
      .contentType("application/json")
      .body("{}")
      .when()
      .post("/api/board/game")
      .`then`()
      .statusCode(201)
      .body("gameId", matchesPattern("[A-Za-z0-9]{8}"))
      .body("state.fen", notNullValue())
      .body("state.turn", equalTo("white"))
      .body("state.status", equalTo("started"))

  @Test
  def createGameWithPlayersReturns201(): Unit =
    RestAssured
      .`given`()
      .contentType("application/json")
      .body("""{"white":{"id":"p1","displayName":"Alice"},"black":{"id":"p2","displayName":"Bob"}}""")
      .when()
      .post("/api/board/game")
      .`then`()
      .statusCode(201)
      .body("white.id", equalTo("p1"))
      .body("black.displayName", equalTo("Bob"))

  @Test
  def getGameReturns200ForExistingGame(): Unit =
    val gameId = RestAssured
      .`given`()
      .contentType("application/json")
      .body("{}")
      .when()
      .post("/api/board/game")
      .`then`()
      .statusCode(201)
      .extract()
      .path[String]("gameId")

    RestAssured
      .`given`()
      .when()
      .get(s"/api/board/game/$gameId")
      .`then`()
      .statusCode(200)
      .body("gameId", equalTo(gameId))

  @Test
  def getGameReturns404ForUnknownId(): Unit =
    RestAssured
      .`given`()
      .when()
      .get("/api/board/game/XXXXXXXX")
      .`then`()
      .statusCode(404)

  @Test
  def createGameWithNullBodyReturns201(): Unit =
    RestAssured
      .`given`()
      .contentType("application/json")
      .body("null")
      .when()
      .post("/api/board/game")
      .`then`()
      .statusCode(201)

  @Test
  def exportPgnOnUnknownGameReturns404(): Unit =
    RestAssured
      .`given`()
      .when()
      .get("/api/board/game/XXXXXXXX/export/pgn")
      .`then`()
      .statusCode(404)

  @Test
  def resignWhenAlreadyResignedReturns400(): Unit =
    val gameId = RestAssured
      .`given`()
      .contentType("application/json")
      .body("{}")
      .when()
      .post("/api/board/game")
      .`then`()
      .statusCode(201)
      .extract()
      .path[String]("gameId")
    RestAssured
      .`given`()
      .when()
      .post(s"/api/board/game/$gameId/resign")
      .`then`()
      .statusCode(200)
    RestAssured
      .`given`()
      .when()
      .post(s"/api/board/game/$gameId/resign")
      .`then`()
      .statusCode(400)
