/**
 * AI Avatar — Conversation Persistence
 * --------------------------------------
 * Simple CRUD operations for saving and loading avatar conversations.
 *
 * How it works:
 *   1. When a user sends their FIRST message, a new conversation is created
 *   2. Each user message and assistant reply are saved as AvatarMessage rows
 *   3. The conversation title is auto-generated from the first user message
 *   4. Recent conversations can be loaded for the sidebar/history list
 *
 * The frontend sends a `conversationId` (or null for new conversations).
 * The backend returns the conversationId so the frontend can keep using it.
 */

import { prisma } from "@/lib/prisma";

// ─── Types ───────────────────────────────────────────────────────────────────

export interface SavedConversation {
  id: string;
  title: string;
  updatedAt: Date;
  messageCount: number;
  /** Preview of the last message */
  lastMessage: string;
}

// ─── Create a new conversation ───────────────────────────────────────────────

export async function createConversation(
  userId: string,
  brandId: string,
  firstMessage: string
): Promise<string> {
  // Auto-generate a title from the first message (truncate to 60 chars)
  const title = firstMessage.length > 60
    ? firstMessage.slice(0, 57) + "..."
    : firstMessage;

  const conversation = await prisma.avatarConversation.create({
    data: {
      title,
      userId,
      brandId,
    },
  });

  return conversation.id;
}

// ─── Save a message to a conversation ────────────────────────────────────────

export async function saveMessage(
  conversationId: string,
  role: "user" | "assistant",
  content: string,
  module?: string,
  metadata?: Record<string, unknown>
): Promise<void> {
  await prisma.avatarMessage.create({
    data: {
      conversationId,
      role,
      content,
      module: module ?? null,
      metadata: metadata ? JSON.parse(JSON.stringify(metadata)) : {},
    },
  });

  // Update the conversation's updatedAt timestamp
  await prisma.avatarConversation.update({
    where: { id: conversationId },
    data: { updatedAt: new Date() },
  });
}

// ─── Load messages for a conversation ────────────────────────────────────────

export async function loadConversationMessages(
  conversationId: string,
  userId: string
): Promise<{
  id: string;
  title: string;
  messages: Array<{
    id: string;
    role: string;
    content: string;
    module: string | null;
    metadata: unknown;
    createdAt: Date;
  }>;
} | null> {
  const conversation = await prisma.avatarConversation.findUnique({
    where: { id: conversationId },
    include: {
      messages: {
        orderBy: { createdAt: "asc" },
      },
    },
  });

  // Permission check — only the owner can load their conversations
  if (!conversation || conversation.userId !== userId) return null;

  return {
    id: conversation.id,
    title: conversation.title,
    messages: conversation.messages,
  };
}

// ─── List recent conversations for a user + brand ────────────────────────────

export async function listRecentConversations(
  userId: string,
  brandId: string,
  limit: number = 20
): Promise<SavedConversation[]> {
  const conversations = await prisma.avatarConversation.findMany({
    where: { userId, brandId },
    orderBy: { updatedAt: "desc" },
    take: limit,
    include: {
      messages: {
        orderBy: { createdAt: "desc" },
        take: 1,
        select: { content: true },
      },
      _count: {
        select: { messages: true },
      },
    },
  });

  return conversations.map((c) => ({
    id: c.id,
    title: c.title,
    updatedAt: c.updatedAt,
    messageCount: c._count.messages,
    lastMessage: c.messages[0]?.content.slice(0, 80) ?? "",
  }));
}

// ─── Delete a conversation ───────────────────────────────────────────────────

export async function deleteConversation(
  conversationId: string,
  userId: string
): Promise<boolean> {
  const conversation = await prisma.avatarConversation.findUnique({
    where: { id: conversationId },
  });

  if (!conversation || conversation.userId !== userId) return false;

  await prisma.avatarConversation.delete({
    where: { id: conversationId },
  });

  return true;
}
