/**
 * GET  /api/ai-recommendations?brandId=…&status=…&type=…
 * POST /api/ai-recommendations  { action: "update_status", id, status }
 * POST /api/ai-recommendations  { action: "generate", brandId }
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  getRecommendations,
  getRecommendationCounts,
  updateRecommendationStatus,
  generateRecommendations,
} from "@/lib/intelligence/ai-strategy-engine";

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 url = new URL(req.url);
  const brandId = url.searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

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

  const status = url.searchParams.get("status") ?? undefined;
  const type = url.searchParams.get("type") ?? undefined;
  const countsOnly = url.searchParams.get("counts") === "true";

  if (countsOnly) {
    const counts = await getRecommendationCounts(brandId);
    return NextResponse.json(counts);
  }

  const recommendations = await getRecommendations(brandId, { status, type });
  const counts = await getRecommendationCounts(brandId);

  return NextResponse.json({ recommendations, counts });
}

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);
  if (!body?.action) return NextResponse.json({ error: "action required" }, { status: 400 });

  if (body.action === "update_status") {
    if (!body.id || !body.status) {
      return NextResponse.json({ error: "id and status required" }, { status: 400 });
    }

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

    await updateRecommendationStatus(body.id, body.status);
    return NextResponse.json({ ok: true });
  }

  if (body.action === "generate") {
    if (!body.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

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

    const result = await generateRecommendations(body.brandId);
    return NextResponse.json(result);
  }

  return NextResponse.json({ error: "Unknown action" }, { status: 400 });
}
