import { onRequest } from "firebase-functions/https"; import { requireAuth } from "../middleware/auth"; import { sendError } from "../middleware/errors"; import { getWallet } from "../repositories/walletRepository"; import { listLedger } from "../repositories/pointLedgerRepository"; import { getCatalog, getCatalogProduct } from "../services/rewardCatalogService"; import { computeEligibility } from "../services/eligibilityService"; import { cancelOrder, createOrder, getOrder, listOrders } from "../services/orderService"; export const reward = onRequest(async (req, res) => { try { const uid = await requireAuth(req); const path = req.path.replace(/^\/+|\/+$/g, ""); if (req.method === "GET" && path === "wallet") { res.json((await getWallet(uid)) ?? { availableBalance: 0, reservedBalance: 0, totalEarned: 0, totalSpent: 0, version: 0 }); return; } if (req.method === "GET" && path === "ledger") { res.json(await listLedger(uid, Number(req.query.limit) || 20, typeof req.query.cursor === "string" ? req.query.cursor : undefined)); return; } if (req.method === "GET" && path === "products") { res.json(await getCatalog()); return; } const product = path.match(/^products\/([^/]+)$/); if (req.method === "GET" && product) { const p = await getCatalogProduct(product[1]); if (!p) { res.status(404).json({ error: "PRODUCT_NOT_FOUND" }); return; } res.json(p); return; } if (req.method === "GET" && path === "eligibility") { res.json(await computeEligibility(uid)); return; } if (req.method === "POST" && path === "orders") { res.status(201).json(await createOrder(uid, req.body)); return; } if (req.method === "GET" && path === "orders") { res.json(await listOrders(uid, Number(req.query.limit) || 20, typeof req.query.cursor === "string" ? req.query.cursor : undefined)); return; } const order = path.match(/^orders\/([^/]+)$/); if (req.method === "GET" && order) { const o = await getOrder(order[1]); if (!o || o.uid !== uid) { res.status(404).json({ error: "ORDER_NOT_FOUND" }); return; } res.json(o); return; } const cancel = path.match(/^orders\/([^/]+)\/cancel$/); if (req.method === "POST" && cancel) { res.json(await cancelOrder(uid, cancel[1])); return; } res.status(404).json({ error: "not found" }); } catch (err) { sendError(res, err); } });