/**
 * Product/Service Library query helpers — thin wrapper over catalog.ts.
 *
 * Provides invoice-oriented aliases for the marketing catalog functions.
 * Route files import from this module, not catalog.ts directly, so the
 * naming is domain-appropriate for the invoicing context.
 *
 * All functions take (db, tenantId, ...) — tenant isolation enforced in catalog.ts.
 * No raw Drizzle from routes (no-raw-drizzle-from-routes ESLint rule).
 */
import {
  listCatalogItems,
  searchCatalogItems,
  getCatalogItem,
  type CatalogItemObject,
} from './catalog'
import type { Db } from '../client'

export type { CatalogItemObject }

// ── Invoice line item data shape ──────────────────────────────────────────────

export interface InvoiceLineItemData {
  description: string
  quantity: string
  unitPrice: string
  discountPct: string
  lineTotal: string
  taxable: boolean
  /** Source catalog item id for reference */
  catalogItemId: string
}

// ── Aliases ───────────────────────────────────────────────────────────────────

/**
 * Returns all active products/services for a tenant.
 * Alias for `listCatalogItems` with `activeOnly: true`.
 */
export async function getProductLibrary(
  db: Db,
  tenantId: string,
  opts: { category?: string } = {},
): Promise<CatalogItemObject[]> {
  return listCatalogItems(db, tenantId, { ...opts, activeOnly: true })
}

/**
 * Full-text search over name, description, SKU, category.
 * Alias for `searchCatalogItems`.
 */
export async function searchProducts(
  db: Db,
  tenantId: string,
  query: string,
): Promise<CatalogItemObject[]> {
  return searchCatalogItems(db, tenantId, query)
}

/**
 * Returns pre-filled invoice line item data from a catalog item.
 * Quantity defaults to 1 and discount to 0 — caller adjusts before save.
 */
export async function addProductToInvoiceLine(
  db: Db,
  tenantId: string,
  catalogItemId: string,
): Promise<InvoiceLineItemData | null> {
  const item = await getCatalogItem(db, tenantId, catalogItemId)
  if (!item) return null

  const unitPrice = item.unitPrice
  const quantity = '1'
  const discountPct = '0'
  const lineTotal = (parseFloat(unitPrice) * parseFloat(quantity)).toFixed(2)

  return {
    description: item.name + (item.description ? ` — ${item.description}` : ''),
    quantity,
    unitPrice,
    discountPct,
    lineTotal,
    taxable: true,
    catalogItemId: item.id,
  }
}
