/**
 * PATCH  /api/ai-strategist/sessions/[id] — update title
 * DELETE /api/ai-strategist/sessions/[id] — delete session + messages
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

  const session = await prisma.strategistSession.findUnique({ where: { id: params.id }, select: { userId: true } });
  if (!session || session.userId !== user.id) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const { title } = (await req.json()) as { title: string };
  await prisma.strategistSession.update({ where: { id: params.id }, data: { title: title.slice(0, 100) } });
  return NextResponse.json({ ok: true });
}

export async function DELETE(_req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const session = await prisma.strategistSession.findUnique({ where: { id: params.id }, select: { userId: true } });
  if (!session || session.userId !== user.id) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await prisma.strategistSession.delete({ where: { id: params.id } });
  return NextResponse.json({ ok: true });
}
