'use server'

import { db } from '@/lib/db'
import { requireSession } from '@/lib/auth'
import { rebuildSearchText } from '@/lib/search'
import { revalidatePath } from 'next/cache'
import {
  getLatestSession,
  getQueueDepth,
  getSession,
  startSession,
  type AIReviewSessionRow,
} from '@/lib/ai-review-session'

interface ApplyInput {
  name: string
  category: string | null
  brand: string | null
  tags: string[]
}

export async function applySuggestion(jobId: string, input: ApplyInput) {
  await requireSession()
  const job = await db.identificationJob.findUnique({
    where: { id: jobId },
    include: { photo: true },
  })
  if (!job) return
  const itemId = job.photo.itemId
  const tagNames = Array.from(
    new Set(input.tags.map(t => t.trim().toLowerCase()).filter(Boolean)),
  ).slice(0, 20)

  await db.$transaction(async tx => {
    await tx.item.update({
      where: { id: itemId },
      data: {
        name: input.name.trim() || 'Untitled item',
        category: input.category?.trim() || null,
        brand: input.brand?.trim() || null,
        tags: {
          connectOrCreate: tagNames.map(n => ({
            where: { name: n },
            create: { name: n },
          })),
        },
      },
    })
    await tx.identificationJob.update({
      where: { id: jobId },
      data: { status: 'DONE', processedAt: new Date() },
    })
    await rebuildSearchText(tx, itemId)
  })

  revalidatePath('/identify')
  revalidatePath('/')
  revalidatePath(`/items/${itemId}`)
}

export async function skipSuggestion(jobId: string) {
  await requireSession()
  await db.identificationJob.update({
    where: { id: jobId },
    data: { status: 'SKIPPED', processedAt: new Date() },
  })
  revalidatePath('/identify')
}

export interface StartSessionResult {
  ok: boolean
  sessionId?: string
  error?: string
}

export async function startAIReviewSessionAction(): Promise<StartSessionResult> {
  const session = await requireSession()
  try {
    const { sessionId } = await startSession({ triggeredById: session.userId })
    revalidatePath('/identify')
    return { ok: true, sessionId }
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : 'Failed to start session',
    }
  }
}

export interface AIReviewSnapshot {
  queueDepth: number
  latest: AIReviewSessionRow | null
}

export async function fetchAIReviewSnapshot(): Promise<AIReviewSnapshot> {
  await requireSession()
  const [queueDepth, latest] = await Promise.all([getQueueDepth(), getLatestSession()])
  return { queueDepth, latest }
}

export async function fetchAIReviewSession(id: string): Promise<AIReviewSessionRow | null> {
  await requireSession()
  return getSession(id)
}
