/** * POST /api/players/ensure-match * Body: { account_id, match_id } * Auth: logged-in self, or target user has public_share. * Loads Climperor match detail from R2, or fetches+normalizes from OpenDota. */ import { sessionFromRequest } from "../auth/_steam_common.js"; import { jsonResponse } from "./_db.js"; import { ensureNormalizedMatch } from "./_match.js"; function intField(v, fallback = 0) { const n = Number(v); return Number.isFinite(n) ? Math.trunc(n) : fallback; } export async function onRequestPost(context) { try { const env = context.env || {}; if (!env.DB) return jsonResponse({ error: "database not configured" }, 503); if (!env.MATCHES) return jsonResponse({ error: "storage not configured" }, 503); let body; try { body = await context.request.json(); } catch { return jsonResponse({ error: "invalid json" }, 400); } const accountId = intField(body && body.account_id, -1); const matchId = intField(body && body.match_id, -1); if (accountId <= 0 || matchId <= 0) { return jsonResponse({ error: "account_id and match_id required" }, 400); } const session = await sessionFromRequest(context); const self = session && Number(session.account_id) === accountId; const user = await env.DB.prepare( `SELECT public_share FROM users WHERE account_id = ?` ) .bind(accountId) .first(); if (!user) return jsonResponse({ error: "not found" }, 404); if (!self && !user.public_share) { return jsonResponse({ error: "private" }, 404); } const { match, error } = await ensureNormalizedMatch(env, accountId, matchId); if (!match) { return jsonResponse( { error: error || "unknown", account_id: accountId, match_id: matchId }, 404 ); } return jsonResponse({ ok: true, match }); } catch (e) { return jsonResponse( { error: "ensure-match failed", detail: String((e && e.message) || e) }, 500 ); } } export async function onRequestOptions() { return new Response(null, { status: 204, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Access-Control-Max-Age": "86400", }, }); }