package de.szut.casino.blackjack;

import de.szut.casino.exceptionHandling.exceptions.UserBlackJackGameMismatchException;
import de.szut.casino.shared.dto.BetDto;
import de.szut.casino.user.UserEntity;
import de.szut.casino.user.UserService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@Slf4j
@RestController
public class BlackJackGameController {

    private final UserService userService;
    private final BlackJackService blackJackService;

    public BlackJackGameController(UserService userService, BlackJackService blackJackService) {
        this.blackJackService = blackJackService;
        this.userService = userService;
    }

    @GetMapping("/blackjack/{id}")
    public ResponseEntity<Object> getGame(@PathVariable Long id) {
        BlackJackGameEntity game = getBlackJackGame(id);

        return ResponseEntity.ok(game);
    }

    @PostMapping("/blackjack/{id}/hit")
    public ResponseEntity<Object> hit(@PathVariable Long id) {
        BlackJackGameEntity game = getBlackJackGame(id);

        return ResponseEntity.ok(blackJackService.hit(game));
    }

    @PostMapping("/blackjack/{id}/stand")
    public ResponseEntity<Object> stand(@PathVariable Long id) {
        BlackJackGameEntity game = getBlackJackGame(id);

        return ResponseEntity.ok(blackJackService.stand(game));
    }

    @PostMapping("/blackjack/{id}/doubleDown")
    public ResponseEntity<Object> doubleDown(@PathVariable Long id) {
        BlackJackGameEntity game = getBlackJackGame(id);

        return ResponseEntity.ok(blackJackService.doubleDown(game));
    }

    @PostMapping("/blackjack/start")
    public ResponseEntity<Object> createBlackJackGame(@RequestBody @Valid BetDto betDto) {
        return ResponseEntity.ok(blackJackService.createBlackJackGame(betDto));
    }

    private BlackJackGameEntity getBlackJackGame(Long gameId) {
        UserEntity user = userService.getCurrentUser();
        BlackJackGameEntity game = blackJackService.getBlackJackGame(gameId);
        if (game == null || !Objects.equals(game.getUserId(), user.getId())) {
            throw new UserBlackJackGameMismatchException(gameId);
        }

        return game;
    }
}
