'use server'

import { chatService } from '@/lib/ai/services'
import { auth } from '@/auth'
import { revalidatePath } from 'next/cache'
import { prisma } from '@/lib/prisma'

/**
 * Create a new empty conversation and return its id.
 * Called before streaming so the client knows the conversationId upfront.
 */
export async function createConversation(title: string, notebookId?: string) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  const conversation = await prisma.conversation.create({
    data: {
      userId: session.user.id,
      notebookId: notebookId || null,
      title: title.substring(0, 80) + (title.length > 80 ? '...' : ''),
    },
  })

  revalidatePath('/chat')
  return { id: conversation.id, title: conversation.title }
}

/**
 * @deprecated Use the streaming API route /api/chat instead.
 * Kept for backward compatibility with the debug route.
 */
export async function sendChatMessage(
  message: string,
  conversationId?: string,
  notebookId?: string
) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  try {
    const result = await chatService.chat(message, conversationId, notebookId)
    revalidatePath('/chat')
    return { success: true, ...result }
  } catch (error: any) {
    console.error('[ChatAction] Error:', error)
    return { success: false, error: error.message }
  }
}

export async function getConversations() {
  const session = await auth()
  if (!session?.user?.id) return []

  return chatService.listConversations(session.user.id)
}

export async function getConversationDetails(id: string) {
  const session = await auth()
  if (!session?.user?.id) return null

  return chatService.getHistory(id)
}

export async function deleteConversation(id: string) {
  const session = await auth()
  if (!session?.user?.id) throw new Error('Unauthorized')

  await prisma.conversation.delete({
    where: { id, userId: session.user.id }
  })

  revalidatePath('/chat')
  return { success: true }
}
