import { getCurrentUser, requireRole, json, error, ROLE_RANK } from "../_utils.js"; const TYPES = ["game", "movie", "link"]; // GET /api/content?type=game&status=published export async function onRequestGet({ request, env }) { const user = await getCurrentUser(request, env); const denied = requireRole(user, "member"); if (denied) return denied; const url = new URL(request.url); const type = url.searchParams.get("type"); let status = url.searchParams.get("status") || "published"; // Only moderator+ may look at pending/rejected queues. if (status !== "published" && ROLE_RANK[user.role] < ROLE_RANK.moderator) { status = "published"; } if (type && !TYPES.includes(type)) return error("Invalid type."); const query = type ? env.DB.prepare( `SELECT c.*, u.email AS created_by_email FROM content c JOIN users u ON u.id = c.created_by WHERE c.type = ? AND c.status = ? ORDER BY c.created_at DESC` ).bind(type, status) : env.DB.prepare( `SELECT c.*, u.email AS created_by_email FROM content c JOIN users u ON u.id = c.created_by WHERE c.status = ? ORDER BY c.created_at DESC` ).bind(status); const rows = await query.all(); return json({ content: rows.results }); } // POST /api/content { type, title, description, url } // Moderator/Admin/Owner -> published immediately ("Import"). // Member -> saved as pending ("Request to add"). // A "movie" is just a link (e.g. a shared Google Drive video URL), same as // games/links — nothing is uploaded or stored on the server. export async function onRequestPost({ request, env }) { const user = await getCurrentUser(request, env); const denied = requireRole(user, "member"); if (denied) return denied; const body = await request.json().catch(() => ({})); const { type, title, description, url } = body; if (!TYPES.includes(type)) return error("Invalid content type."); if (!title || !title.trim()) return error("Title is required."); if (!url || !url.trim()) return error("A URL is required."); const isImporter = ROLE_RANK[user.role] >= ROLE_RANK.moderator; const id = crypto.randomUUID(); await env.DB.prepare( `INSERT INTO content (id, type, title, description, url, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)` ) .bind(id, type, title.trim(), description || null, url.trim(), isImporter ? "published" : "pending", user.id) .run(); return json({ ok: true, published: isImporter, message: isImporter ? "Added." : "Request submitted for review.", }); }