// app/api/support/kofi/unlink/route.ts import { NextRequest, NextResponse } from "next/server"; const DIRECTUS = (process.env.DIRECTUS_URL || "").replace(/\/$/, ""); const BOT_TOKEN = process.env.DIRECTUS_TOKEN_ADMIN_SUPPORTER!; const COLLECTION = "user_memberships"; // Replace with your real auth/session async function getCurrentUserId(req: NextRequest): Promise { const uid = req.headers.get("x-user-id"); return uid && uid.trim() ? uid : null; } export async function POST(req: NextRequest) { const userId = await getCurrentUserId(req); if (!userId) { return NextResponse.json({ error: "unauthorized" }, { status: 401 }); } // Find linked Ko-fi rows const filter = encodeURIComponent( JSON.stringify({ _and: [{ provider: { _eq: "kofi" } }, { app_user: { _eq: userId } }], }) ); const list = await fetch( `${DIRECTUS}/items/${COLLECTION}?filter=${filter}&limit=500`, { headers: { Authorization: `Bearer ${BOT_TOKEN}` }, cache: "no-store" } ); if (!list.ok) { const t = await list.text().catch(() => ""); return NextResponse.json({ error: "directus_read_failed", detail: t }, { status: 500 }); } const rows = (await list.json()).data || []; if (!rows.length) return NextResponse.json({ ok: true, changed: 0 }); // Batch PATCH: clear app_user const body = rows.map((r: any) => ({ id: r.id, app_user: null, last_event_at: new Date().toISOString(), })); const res = await fetch(`${DIRECTUS}/items/${COLLECTION}`, { method: "PATCH", headers: { "Content-Type": "application/json", Authorization: `Bearer ${BOT_TOKEN}`, }, body: JSON.stringify(body), }); if (!res.ok) { const t = await res.text().catch(() => ""); return NextResponse.json({ error: "directus_write_failed", detail: t }, { status: 500 }); } return NextResponse.json({ ok: true, changed: rows.length }); }