/**
 * GET /api/rank-tracking/history?keywordId=X&days=90
 * Returns daily KeywordRanking records for the position trend chart.
 */

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

export const dynamic = "force-dynamic";

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

  const { searchParams } = new URL(req.url);
  const keywordId = searchParams.get("keywordId");
  if (!keywordId) return NextResponse.json({ error: "keywordId required" }, { status: 400 });

  const kw = await prisma.trackedKeyword.findUnique({
    where: { id: 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 });
  }

  const days = Math.max(1, Math.min(365, Number(searchParams.get("days") || 90)));
  const since = new Date(Date.now() - days * 86400000);

  const rankings = await prisma.keywordRanking.findMany({
    where: { trackedKeywordId: keywordId, checkedAt: { gte: since } },
    orderBy: { checkedAt: "asc" },
    select: { position: true, previousPosition: true, url: true, snippet: true, checkedAt: true, source: true },
  });

  return NextResponse.json({ keyword: kw.keyword, location: kw.location, device: kw.device, rankings });
}
