const express = require("express");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 3001;
const {
  getGameState,
  updateGameState,
  startGameLoop,
} = require("./game-logic");

app.use(cors());
app.use(express.json());

// Get current game state
app.get("/api/game", (req, res) => {
  const gameState = getGameState();
  console.log("API /game called, current round:", gameState.currentRound);
  res.set({
    "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
    Pragma: "no-cache",
    Expires: "0",
  });
  res.json(gameState);
});

// Submit a vote
app.post("/api/vote", (req, res) => {
  try {
    const { choice } = req.body;
    console.log("Vote received:", choice);

    if (!choice || (choice !== "PLAYER" && choice !== "BANKER")) {
      return res.status(400).json({
        error: "Invalid choice. Must be PLAYER or BANKER.",
      });
    }

    const state = getGameState(); // Get current state to safely update votes
    const newVotes = {
      player: state.votes.player || 0,
      banker: state.votes.banker || 0,
    };

    if (choice === "BANKER") {
      newVotes.banker++;
    } else if (choice === "PLAYER") {
      newVotes.player++;
    }

    updateGameState({ votes: newVotes });
    console.log("Updated votes:", newVotes);

    res.json({ success: true });
  } catch (error) {
    console.error("Error in /api/vote:", error);
    res.status(400).json({ error: "Invalid request" });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
  startGameLoop(); // Start the game loop
});
