/**
 * POST /api/rank-tracking/backfill  Body: { brandId: string }
 * ──────────────────────────────────────────────────────────────
 * Walks every active TrackedKeyword for the brand and seeds its
 * KeywordRanking history from GscQuery rows already in the database.
 * Used by the "Backfill from GSC" button in the Rank Tracker header.
 *
 * Idempotent — rerunning is a no-op because backfillKeyword() skips
 * dates already covered by an existing KeywordRanking row (live check
 * or prior backfill).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { backfillBrand } from "@/lib/services/rank-tracker-backfill";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null) as { brandId?: string } | null;
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  // Auth — user must belong to the brand's org.
  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const summary = await backfillBrand(body.brandId);
  return NextResponse.json(summary);
}
