/**
 * Blueprint composition proof — commerce catalog + fields faceting (spec Part B).
 *
 * Proves queryEntities → entityIds → listProducts wiring with capped propagation.
 */
import { beforeEach, describe, expect, it } from 'vitest'
import { resolveGroups, setEntityValues } from '@platform-modules/fields'
import { seedProduct, type CatalogDb } from '../src/blueprints/commerce/wiring/catalog'
import {
  createCommerceFacetingDb,
  facetedProductList,
  productAttrsGroup,
  type FieldsDb,
  type SeededCommerceFaceting,
} from '../src/blueprints/commerce/wiring/fields-faceting'

async function setProductColor(
  fieldsDb: FieldsDb,
  seeded: SeededCommerceFaceting,
  productId: string,
  color: string,
) {
  const resolved = (
    await resolveGroups(fieldsDb, {
      entityType: 'product',
      codeGroups: [productAttrsGroup],
    })
  ).find((g) => g.key === 'product_attrs')!
  await setEntityValues(fieldsDb, seeded.fieldsEditor, {
    ref: { entityType: 'product', entityId: productId },
    groupId: 'product_attrs',
    resolved,
    values: { color },
  })
}

describe('commerce faceting wiring (fields queryEntities → catalog listProducts)', () => {
  let seeded: SeededCommerceFaceting
  let catalogDb: CatalogDb
  let fieldsDb: FieldsDb

  beforeEach(async () => {
    seeded = await createCommerceFacetingDb()
    catalogDb = seeded.catalogDb
    fieldsDb = seeded.fieldsDb
  })

  it('faceted list: products outside the candidate set are absent', async () => {
    const prodA = await seedProduct(catalogDb, { slug: 'prod-a', title: 'A', status: 'active' })
    const prodB = await seedProduct(catalogDb, { slug: 'prod-b', title: 'B', status: 'active' })
    await setProductColor(fieldsDb, seeded, prodA.id, 'red')

    const { page } = await facetedProductList(
      fieldsDb,
      catalogDb,
      { entityType: 'product', facets: [{ field: 'color', op: 'eq', value: 'red' }] },
      { audience: 'public' },
    )
    expect(page.items.map((p) => p.id)).toEqual([prodA.id])
  })

  it('propagates catalog-side truncation when engine is not capped (OR both hops)', async () => {
    for (let i = 0; i < 257; i++) {
      const row = await seedProduct(catalogDb, {
        slug: `catalog-cap-${i}`,
        title: `Catalog Cap ${i}`,
        status: 'active',
      })
      await setProductColor(fieldsDb, seeded, row.id, 'red')
    }

    const { capped, page } = await facetedProductList(
      fieldsDb,
      catalogDb,
      { entityType: 'product', facets: [{ field: 'color', op: 'eq', value: 'red' }] },
      { audience: 'public' },
    )
    expect(capped).toBe(true)
    expect(page.entityIdsCapped).toBe(true)
    expect(page.total).toBeLessThanOrEqual(256)
  })

  it('propagates capped from the engine (degrade signal not dropped)', async () => {
    const p1 = await seedProduct(catalogDb, { slug: 'cap-1', title: 'Cap 1', status: 'active' })
    const p2 = await seedProduct(catalogDb, { slug: 'cap-2', title: 'Cap 2', status: 'active' })
    await setProductColor(fieldsDb, seeded, p1.id, 'red')
    await setProductColor(fieldsDb, seeded, p2.id, 'red')

    const { capped } = await facetedProductList(
      fieldsDb,
      catalogDb,
      { entityType: 'product', facets: [{ field: 'color', op: 'eq', value: 'red' }], limit: 1 },
      { audience: 'public' },
    )
    expect(capped).toBe(true)
  })

  it('zero-facet query short-circuits to an empty page (cross-hop empty trap)', async () => {
    await seedProduct(catalogDb, { slug: 'any', title: 'Any', status: 'active' })

    const { page } = await facetedProductList(
      fieldsDb,
      catalogDb,
      { entityType: 'product', facets: [] },
      { audience: 'public' },
    )
    expect(page.items).toEqual([])
  })

  it('non-empty facets with ZERO matches → empty page (the real faceting path)', async () => {
    const prodA = await seedProduct(catalogDb, { slug: 'no-match', title: 'No Match', status: 'active' })
    await setProductColor(fieldsDb, seeded, prodA.id, 'red')

    const { page } = await facetedProductList(
      fieldsDb,
      catalogDb,
      { entityType: 'product', facets: [{ field: 'color', op: 'eq', value: 'chartreuse' }] },
      { audience: 'public' },
    )
    expect(page.items).toEqual([])
  })
})