/**
 * commerce blueprint · wiring seam for `@platform-modules/commerce-catalog`.
 *
 * Host-owned glue: bootstrap catalog tables on a PGlite client and expose a typed
 * Querier handle. Mirrors cms/wiring/content.ts (one client, drizzle schema, migration).
 */
import { PGlite } from '@electric-sql/pglite'
import { drizzle } from 'drizzle-orm/pglite'
import {
  pushSchema,
  catalogSchema,
  upsertProduct,
  type CatalogSchema,
  type Product,
  type ProductKind,
  type ProductStatus,
} from '@platform-modules/commerce-catalog'
import type { TransactionalDatabase } from '@platform-modules/db'

export type CatalogDb = TransactionalDatabase<CatalogSchema>

export type SeededCatalog = {
  client: PGlite
  catalogDb: CatalogDb
}

export async function createCommerceCatalogDb(): Promise<SeededCatalog> {
  const client = new PGlite()
  const catalogDb = drizzle(client, { schema: catalogSchema }) as unknown as CatalogDb
  await pushSchema(catalogDb)
  return { client, catalogDb }
}

export async function seedProduct(
  catalogDb: CatalogDb,
  input: {
    slug: string
    title: string
    status?: ProductStatus
    kind?: ProductKind
    availableFrom?: Date | null
  },
): Promise<Product> {
  return upsertProduct(catalogDb, {
    kind: input.kind ?? 'physical',
    slug: input.slug,
    title: input.title,
    status: input.status ?? 'active',
    availableFrom: input.availableFrom,
  })
}