/**
 * DELETE /api/rank-tracking/keywords/[keywordId]
 * Soft-deletes a tracked keyword (sets isActive: false) to preserve
 * historical ranking data.
 */

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.trackedKeyword.findUnique({
    where: { id: params.keywordId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!kw) return NextResponse.json({ error: "Keyword 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.trackedKeyword.update({
    where: { id: params.keywordId },
    data: { isActive: false },
  });

  return NextResponse.json({ ok: true });
}
