import { onRequest } from "firebase-functions/https"; import { requireAuth } from "../middleware/auth.js"; import { HttpError, sendError } from "../middleware/errors.js"; import { createPrediction, updatePrediction, getMyVotes, getSummary, listGamesByDate, } from "../services/predictionService.js"; import { getScoreboard } from "../services/scoreboardService.js"; export const prediction = onRequest(async (req, res) => { const segs = req.path.replace(/^\/+|\/+$/g, "").split("/"); const tail = segs[segs.length - 1] ?? ""; try { if (tail === "games" && req.method === "GET") { const date = String(req.query.date ?? ""); const games = await listGamesByDate(date); res.status(200).json({ date, games }); return; } if (tail === "scoreboard" && req.method === "GET") { const uid = await requireAuth(req); const type = String(req.query.type ?? ""); if (type !== "team" && type !== "overall") { throw new HttpError(400, `invalid type: ${type}`); } const result = await getScoreboard(uid, type); res.set("Cache-Control", "private, max-age=60"); res.status(200).json(result); return; } if (tail === "summary" && req.method === "GET") { const gameId = String(req.query.gameId ?? ""); const result = await getSummary(gameId); res.set("Cache-Control", "public, max-age=5"); res.status(200).json(result); return; } if (tail === "prediction" || segs.length === 1) { if (req.method === "POST") { const uid = await requireAuth(req); const result = await createPrediction(uid, req.body ?? {}); res.status(201).json(result); return; } if (req.method === "PUT") { const uid = await requireAuth(req); const result = await updatePrediction(uid, req.body ?? {}); res.status(200).json(result); return; } if (req.method === "GET") { const uid = await requireAuth(req); const date = String(req.query.date ?? ""); const result = await getMyVotes(uid, date); res.status(200).json(result); return; } } res.status(404).json({ error: `Unknown: ${req.method} ${req.path}` }); } catch (err) { sendError(res, err); } });