/**
 * RAG index-update enqueue helpers — ai-assistant.
 *
 * These helpers put `AiIndexUpdateJob` messages onto the `QUEUE` binding so
 * the `ai_index_update` consumer can embed and upsert/delete vectors.
 *
 * Per-entity text builders are provided so source modules produce consistent,
 * spec-compliant index text without duplicating the field logic.
 */
import type { Env } from '@zync/types'
import type { IndexableEntity, IndexableEntityType } from './types'
import { vectorIdFor } from './types'

// ── Job type ──────────────────────────────────────────────────────────────────

export type AiIndexUpdateJob =
  | { op: 'upsert'; tenantId: string; entityType: IndexableEntityType; entityId: string; text: string }
  | { op: 'delete'; tenantId: string; entityType: IndexableEntityType; entityId: string }

// ── Enqueue helpers ───────────────────────────────────────────────────────────

/**
 * Enqueue a vector upsert for the given entity.
 * Called on entity create/update.
 */
export async function enqueueIndexUpsert(env: Env, entity: IndexableEntity): Promise<void> {
  const job: AiIndexUpdateJob = {
    op: 'upsert',
    tenantId: entity.tenantId,
    entityType: entity.entityType,
    entityId: entity.entityId,
    text: entity.text,
  }
  await env.QUEUE.send(job)
}

/**
 * Enqueue a vector delete for the given entity reference.
 * Called on entity delete.
 */
export async function enqueueIndexDelete(
  env: Env,
  ref: { tenantId: string; entityType: IndexableEntityType; entityId: string },
): Promise<void> {
  const job: AiIndexUpdateJob = {
    op: 'delete',
    tenantId: ref.tenantId,
    entityType: ref.entityType,
    entityId: ref.entityId,
  }
  await env.QUEUE.send(job)
}

// ── Per-entity text builders ──────────────────────────────────────────────────
// Spec: customers=name/email/contact notes; invoices=amount/status/customer/line items;
//       tasks=title/description/status/assignee; projects=name/type/customer/description;
//       expenses=amount/category/description; kb=full text.

export function buildCustomerIndexText(c: {
  name: string
  email?: string
  notes?: string
}): string {
  const parts = [`Customer: ${c.name}`]
  if (c.email) parts.push(`Email: ${c.email}`)
  if (c.notes) parts.push(`Notes: ${c.notes}`)
  return parts.join('\n')
}

export function buildInvoiceIndexText(i: {
  number: string
  amount: string
  status: string
  customerName?: string
  lineItems: string[]
}): string {
  const parts = [
    `Invoice: ${i.number}`,
    `Amount: ${i.amount}`,
    `Status: ${i.status}`,
  ]
  if (i.customerName) parts.push(`Customer: ${i.customerName}`)
  if (i.lineItems.length > 0) parts.push(`Line items: ${i.lineItems.join(', ')}`)
  return parts.join('\n')
}

export function buildTaskIndexText(t: {
  title: string
  description?: string
  status: string
  assigneeName?: string
}): string {
  const parts = [`Task: ${t.title}`, `Status: ${t.status}`]
  if (t.description) parts.push(`Description: ${t.description}`)
  if (t.assigneeName) parts.push(`Assignee: ${t.assigneeName}`)
  return parts.join('\n')
}

export function buildProjectIndexText(p: {
  name: string
  type?: string
  customerName?: string
  description?: string
}): string {
  const parts = [`Project: ${p.name}`]
  if (p.type) parts.push(`Type: ${p.type}`)
  if (p.customerName) parts.push(`Customer: ${p.customerName}`)
  if (p.description) parts.push(`Description: ${p.description}`)
  return parts.join('\n')
}

export function buildExpenseIndexText(e: {
  amount: string
  category?: string
  description?: string
}): string {
  const parts = [`Expense: ${e.amount}`]
  if (e.category) parts.push(`Category: ${e.category}`)
  if (e.description) parts.push(`Description: ${e.description}`)
  return parts.join('\n')
}

export function buildKbArticleIndexText(a: { title: string; body: string }): string {
  return `Knowledge Base Article: ${a.title}\n\n${a.body}`
}

// Re-export the vectorIdFor helper for consumers that want to pre-compute IDs
export { vectorIdFor }
