/**
 * commerce blueprint · wiring seam for `@platform-modules/fields` composed with catalog.
 *
 * Host-owned glue: run the fields migration on the same PGlite client the catalog fixture
 * uses, then expose facetedProductList — the ONLY place fields + catalog meet.
 */
import { drizzle } from 'drizzle-orm/pglite'
import type { PGlite } from '@electric-sql/pglite'
import {
  queryEntities,
  fieldsMigrationSql,
  fieldsSchema,
  defineFieldGroup,
  type Facet,
  type FieldsSchema,
  type Actor as FieldsActor,
  type CodeFieldGroup,
} from '@platform-modules/fields'
import {
  listProducts,
  type CatalogFilter,
  type CatalogSchema,
  type Page,
  type Product,
} from '@platform-modules/commerce-catalog'
import type { Querier, TransactionalDatabase } from '@platform-modules/db'
import { createCommerceCatalogDb, type CatalogDb } from './catalog.js'

export type FieldsDb = TransactionalDatabase<FieldsSchema>

/** Code-defined group the commerce blueprint mounts for product entries. */
export const productAttrsGroup = defineFieldGroup({
  key: 'product_attrs',
  label: 'Attributes',
  location: { entityType: 'product' },
  fields: [{ type: 'text', key: 'color', label: 'Color' }],
})

export type SeededCommerceFaceting = {
  client: PGlite
  catalogDb: CatalogDb
  fieldsDb: FieldsDb
  fieldsEditor: FieldsActor
  productAttrsGroup: CodeFieldGroup
}

export async function createCommerceFacetingDb(): Promise<SeededCommerceFaceting> {
  const { client, catalogDb } = await createCommerceCatalogDb()
  await client.exec(fieldsMigrationSql())
  const fieldsDb = drizzle(client, { schema: fieldsSchema }) as unknown as FieldsDb
  return {
    client,
    catalogDb,
    fieldsDb,
    fieldsEditor: { id: 'faceting-editor', canEditFields: true, canManageGroups: true },
    productAttrsGroup,
  }
}

/**
 * Compose fields candidate-set query → catalog page. Propagates `capped` (correctness
 * boundary: capped ⇒ result NON-authoritative; UI shows "first N", never the full set).
 */
export async function facetedProductList(
  fieldsDb: Querier<FieldsSchema>,
  catalogDb: Querier<CatalogSchema>,
  facet: { entityType: 'product'; facets: Facet[]; limit?: number },
  catalogFilter: Omit<CatalogFilter, 'entityIds'>,
): Promise<{ page: Page<Product>; capped: boolean }> {
  const { entityIds, capped: engineCapped } = await queryEntities(fieldsDb, facet)
  const page = await listProducts(catalogDb, { ...catalogFilter, entityIds })
  return { page, capped: engineCapped || (page.entityIdsCapped ?? false) }
}