import { Router } from 'express';
import { requireAuth } from '../middleware.js';
import {
  listJackpotBattles,
  getJackpotRound,
  createJackpotBattle,
  placeJackpotBet,
  withdrawJackpotBet,
} from '../services/jackpot.js';

const router = Router();

function handleError(res, err) {
  const status = err.status || 500;
  if (status >= 500) console.error(err);
  res.status(status).json({ error: err.message || 'Request failed' });
}

router.get('/', async (_req, res) => {
  try {
    const battles = await listJackpotBattles();
    res.json({ battles });
  } catch (err) {
    handleError(res, err);
  }
});

router.get('/:id', async (req, res) => {
  try {
    const round = await getJackpotRound(req.params.id);
    if (!round) {
      return res.status(404).json({ error: 'Battle not found' });
    }
    res.json({ round });
  } catch (err) {
    handleError(res, err);
  }
});

/** Create a battle by placing the first bet (no round id). */
router.post('/bet', requireAuth, async (req, res) => {
  try {
    const state = await createJackpotBattle(
      req.session.userId,
      req.body.inventoryItemIds
    );
    res.json({ round: state });
  } catch (err) {
    handleError(res, err);
  }
});

router.post('/:id/bet', requireAuth, async (req, res) => {
  try {
    const state = await placeJackpotBet(
      req.params.id,
      req.session.userId,
      req.body.inventoryItemIds
    );
    res.json({ round: state });
  } catch (err) {
    handleError(res, err);
  }
});

router.post('/:id/withdraw', requireAuth, async (req, res) => {
  try {
    const state = await withdrawJackpotBet(
      req.params.id,
      req.session.userId,
      req.body.inventoryItemIds
    );
    res.json({ round: state });
  } catch (err) {
    handleError(res, err);
  }
});

export default router;
