/**
 * DELETE /api/keyword-research/saved/[keywordId] — remove a saved keyword.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function DELETE(_req: Request, { params }: { params: { keywordId: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const kw = await prisma.savedKeyword.findUnique({
    where: { id: params.keywordId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!kw) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!kw.brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  await prisma.savedKeyword.delete({ where: { id: params.keywordId } });
  return NextResponse.json({ ok: true });
}
