package de.nowchess.backcore.resource

import de.nowchess.backcore.dto.{ApiErrorResponse, ImportFenRequest, ImportPgnRequest}
import de.nowchess.backcore.game.{GameMapper, GameService}
import jakarta.enterprise.context.ApplicationScoped
import jakarta.inject.Inject
import jakarta.ws.rs.*
import jakarta.ws.rs.core.{MediaType, Response}

@Path("/api/board/game/import")
@Produces(Array(MediaType.APPLICATION_JSON))
@Consumes(Array(MediaType.APPLICATION_JSON))
@ApplicationScoped
class ImportResource @Inject() (service: GameService):

  @POST
  @Path("/fen")
  def importFen(req: ImportFenRequest): Response =
    service.importFen(Option(req).getOrElse(ImportFenRequest())) match
      case Right(snap) => Response.status(201).entity(GameMapper.toGameFull(snap)).build()
      case Left(err)   => Response.status(400).entity(ApiErrorResponse("INVALID_FEN", err)).build()

  @POST
  @Path("/pgn")
  def importPgn(req: ImportPgnRequest): Response =
    Option(req) match
      case None => Response.status(400).entity(ApiErrorResponse("INVALID_PGN", "Request body is required")).build()
      case Some(body) =>
        service.importPgn(body.pgn) match
          case Right(snap) => Response.status(201).entity(GameMapper.toGameFull(snap)).build()
          case Left(err)   => Response.status(400).entity(ApiErrorResponse("INVALID_PGN", err)).build()
