/**
 * GET /api/ai-avatar/conversations?brandId=xxx
 * -----------------------------------------------
 * Returns recent conversations for the current user + brand.
 *
 * GET /api/ai-avatar/conversations?brandId=xxx&id=conversationId
 * -----------------------------------------------
 * Returns a single conversation with all its messages.
 *
 * DELETE /api/ai-avatar/conversations?id=conversationId
 * -----------------------------------------------
 * Deletes a conversation.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import {
  listRecentConversations,
  loadConversationMessages,
  deleteConversation,
} from "@/lib/ai-avatar/conversations";

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");
  const convId = searchParams.get("id");

  // Load a specific conversation
  if (convId) {
    const conversation = await loadConversationMessages(convId, user.id);
    if (!conversation) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
    return NextResponse.json(conversation);
  }

  // List recent conversations
  if (!brandId) {
    return NextResponse.json({ error: "brandId required" }, { status: 400 });
  }

  const conversations = await listRecentConversations(user.id, brandId);
  return NextResponse.json(conversations);
}

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

  const { searchParams } = new URL(req.url);
  const convId = searchParams.get("id");

  if (!convId) {
    return NextResponse.json({ error: "id required" }, { status: 400 });
  }

  const deleted = await deleteConversation(convId, user.id);
  if (!deleted) {
    return NextResponse.json({ error: "Not found or not authorized" }, { status: 404 });
  }

  return NextResponse.json({ ok: true });
}
