'use server'

import { db } from '@/lib/db'
import { requireSession } from '@/lib/auth'
import { saveVoiceNote } from '@/lib/images'
import {
  startSearchSession,
  getSearchSession,
  getLatestSearchSession,
  type AISearchSessionRow,
} from '@/lib/ai-search-session'

interface StartOk {
  ok: true
  sessionId: string
}
interface StartErr {
  ok: false
  error: string
}

export async function startAISearchAction(formData: FormData): Promise<StartOk | StartErr> {
  const session = await requireSession()

  const query = (formData.get('query') as string)?.trim() ?? ''
  const audio = formData.get('audio') as File | null
  const audioMime = (formData.get('audioMime') as string) || 'audio/webm'

  if (!query && (!audio || audio.size === 0)) {
    return { ok: false, error: 'Type a description or record a voice clip first.' }
  }

  let savedAudio: Awaited<ReturnType<typeof saveVoiceNote>> | null = null
  if (audio && audio.size > 0) {
    const buf = Buffer.from(await audio.arrayBuffer())
    savedAudio = await saveVoiceNote(buf, audioMime)
  }

  try {
    const res = await startSearchSession({
      query,
      audioPath: savedAudio?.path ?? null,
      audioMime: savedAudio ? audioMime : null,
      triggeredById: session.userId,
    })
    return { ok: true, sessionId: res.sessionId }
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : 'Failed to start AI search' }
  }
}

export async function fetchAISearchSession(id: string): Promise<AISearchSessionRow | null> {
  await requireSession()
  return getSearchSession(id)
}

export async function fetchLatestAISearchSession(): Promise<AISearchSessionRow | null> {
  await requireSession()
  return getLatestSearchSession()
}

import type { SearchResult } from '@/lib/search'

export async function loadResultItems(ids: string[]): Promise<SearchResult[]> {
  await requireSession()
  if (ids.length === 0) return []
  const items = await db.item.findMany({
    where: { id: { in: ids } },
    include: {
      location: true,
      photos: {
        where: { isPrimary: true },
        take: 1,
      },
    },
  })
  const byId = new Map(items.map(i => [i.id, i]))
  // Preserve Claude's ranking order; that's the confidence signal.
  return ids
    .map(id => byId.get(id))
    .filter((i): i is NonNullable<typeof i> => Boolean(i))
    .map(i => ({
      id: i.id,
      name: i.name,
      description: i.description,
      category: i.category,
      status: i.status,
      qty: i.qty,
      locationId: i.locationId,
      locationName: i.location.name,
      locationPath: i.location.path,
      thumbPath: i.photos[0]?.thumbPath ?? null,
      needsAIReview: i.needsAIReview,
      similarity: 1,
    }))
}
