/**
 * GET  /api/ai-strategist/sessions?brandId=X — list sessions
 * POST /api/ai-strategist/sessions — create new session { brandId }
 */
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 brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  // Only return sessions that have at least one message. Empty sessions are
  // created eagerly on page load (to keep `sessionId` stable for the first
  // send) and would otherwise flood the sidebar with blank entries.
  const sessions = await prisma.strategistSession.findMany({
    where: { brandId, userId: user.id, messages: { some: {} } },
    orderBy: { updatedAt: "desc" },
    take: 50,
    select: {
      id: true, title: true, createdAt: true, updatedAt: true,
      messages: { orderBy: { createdAt: "asc" }, take: 1, select: { content: true, role: true } },
    },
  });

  return NextResponse.json(sessions.map((s) => ({
    id: s.id,
    title: s.title,
    preview: s.messages[0]?.content.slice(0, 100) ?? "",
    createdAt: s.createdAt.toISOString(),
    updatedAt: s.updatedAt.toISOString(),
  })));
}

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

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

  const session = await prisma.strategistSession.create({
    data: { brandId, userId: user.id },
  });

  return NextResponse.json({ id: session.id, title: session.title });
}
