// Auteur : Simon-Pierre Boucher — contact@spboucher.ai // Toggle d'un favori « Mon univers Ka » : pousse « add » / « remove » au hub // groupe-ka.com (POST signé HMAC, SYNCHRONE — un échec remonte au client). // item_id = identifiant stable du résultat, dérivé de son URL si absent. import { NextRequest, NextResponse } from "next/server"; import { SESSION_COOKIE, readSession } from "@/lib/ka-auth"; import { cleanItem, hubToggle, itemIdForUrl } from "@/lib/hubfav"; export async function POST(req: NextRequest) { const session = readSession(req.cookies.get(SESSION_COOKIE)?.value); if (!session) { return NextResponse.json({ error: "Connexion KA ID requise." }, { status: 401 }); } let body: { action?: unknown; item?: unknown }; try { body = await req.json(); } catch { return NextResponse.json({ error: "Corps JSON invalide." }, { status: 400 }); } const action = body.action; if (action !== "add" && action !== "remove") { return NextResponse.json( { error: "action doit être « add » ou « remove »." }, { status: 400 }, ); } if (typeof body.item !== "object" || body.item === null) { return NextResponse.json({ error: "item requis." }, { status: 400 }); } const item = cleanItem(body.item as Record); if (!item.item_id && item.url) item.item_id = itemIdForUrl(item.url); if (!item.item_id) { return NextResponse.json( { error: "item.item_id ou item.url requis." }, { status: 400 }, ); } if (action === "add" && !item.title) { return NextResponse.json({ error: "item.title requis." }, { status: 400 }); } const ok = await hubToggle(session.ka_id, action, item); if (!ok) { return NextResponse.json( { error: "Le hub Groupe KA est momentanément injoignable." }, { status: 502 }, ); } return NextResponse.json({ ok: true, action, item_id: item.item_id }); }